You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言结构体元素随机命名问题:book.title与book.author无输出

问题分析与修复方案

你的代码里导致title和author为空的核心问题有几个:

1. 循环条件错误,字符从未写入

  • title的循环条件是for(int i =1 ; i < 1;i++),初始i=1时i<1直接不成立,循环一次都不会执行,title数组完全没被赋值。
  • author的循环条件里重复调用randInit(10,20),每次迭代都会重新生成随机上限,而且索引从1开始,跳过了字符串的第一个字符位置。

2. 缺少字符串终止符'\0'

C语言的字符串必须以'\0'结尾才能被正确识别和打印,你的代码没有给title和author添加这个终止符,即使写入了字符,打印时也可能出现乱码或被判定为空。

3. 随机数未初始化种子

虽然这不会直接导致字符串为空,但每次运行程序生成的随机数都会完全一样,需要在程序开头调用srand(time(NULL))初始化随机种子。


修复后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

typedef struct Book{
    char title[20];
    char author[20];
    int pages;
    double price;
}Book;

int randInit(int min, int max){
    return min + rand()%(max - min + 1);
}

void rand_Init_Book(Book *b){
    // 生成title随机字符串
    int title_len = randInit(10, 19); // 留一个位置给'\0'
    for(int i = 0; i < title_len; i++){
        b->title[i] = (char)randInit('a', 'z');
    }
    b->title[title_len] = '\0'; // 添加字符串终止符

    // 生成author随机字符串
    int author_len = randInit(10, 19);
    for(int i = 0; i < author_len; i++){
        b->author[i] = (char)randInit('a', 'z');
    }
    b->author[author_len] = '\0';

    b->pages = randInit(5, 2000);
    b->price = (100 + rand()%(10000-100))/100.0;    
}

int main(){
    srand(time(NULL)); // 初始化随机种子
    Book my_book;
    rand_Init_Book(&my_book);

    printf("Title: %s\n", my_book.title);
    printf("Author: %s\n", my_book.author);
    printf("Pages: %d\n", my_book.pages);
    printf("Price: %.2f\n", my_book.price);

    return 0;
}

关键修复点说明

  • 循环索引从0开始,覆盖字符串的第一个字符位置。
  • 提前生成固定的字符串长度,避免循环条件中重复调用随机函数导致长度不稳定,同时长度限制在19以内,预留一个位置给'\0',防止数组越界。
  • 每个字符串末尾添加'\0',确保能被正确打印。
  • 添加srand(time(NULL))初始化随机种子,让每次运行生成的随机内容都不同。

内容的提问来源于stack exchange,提问作者Валентин Д.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 00:45:12