c - C 程序输出随机数

标签 c arrays random numbers

我正在编写一个程序,要求用户提供姓名和 ID 号...然后我添加了一个搜索功能,例如搜索名称“bob”,它说“Bob 在数组位置 x 中找到,ID 为: xxxxx”

我的问题是代码的“ID:xxxx”部分给了我随机数...它应该是例如 1234,但它给了我类似 4210832 的东西

这是代码

void search_surname()
{
    int index, found=0;
    char surname_to_find[10];

    printf("Please enter the student surname to search for\n\n");
    gets(surname_to_find);
    fflush(stdin);
    system("cls");
    for(index=0;index<height_of_array;index++)
    {

        if(strcmpi(surname_to_find, surname[index]) == 0)
        {
            found=1;

            system("cls");                                                      
            printf("%s found in array position %i, with the ID: %i \n\n", surname_to_find,     
            index+1, id[array_index] );
            getch();

我不是 100% 确定为什么它给我随机数

谢谢。

最佳答案

您发布的代码非常不完整,无法指出确切的答案。因此,有一种解决问题的方法:

  • 首先,你使用 id[array_index] 而不是 id[index] 很奇怪,因为 index 是你的 for 循环。 (array_index 未在您的函数中定义;它是全局变量吗?请避免使用全局变量!)。
  • 示例代码中没有任何 id 被填充,甚至没有被声明。确认填写正确。使用id而不先填写值会打印出奇怪的东西(它未初始化)。调试器应该使确认其正确填充变得容易。否则,只需循环它并打印出来。
  • 使用调试器观察程序的运行情况。

最后一件事:C 有结构。没有理由像这样使用多个数组。

struct surname_info {
    unsigned int id;
    const char *surname;
};
⋮
struct surname_info surnames[10];
surnames[0].id = 1234;
surnames[0].surname = "Bob";
/* etc */

关于c - C 程序输出随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10706179/

相关文章:

ios - 如何将绑定(bind)数组分成自动填充表格的部分?

c - C++ vector 的最佳 C 实现是什么?

javascript - 为什么它夺走了我的功能并使其不再是一个功能?

c - C 中的 LRU 缓存设计,大小有限

c - golang 将内存转换为结构

objective-c - 在这种情况下使用 CFMutableArrayRef 是否更明智?

random - Rust GSL 库总是为随机数生成器返回相同的数字

C函数错误: is it better to abort the function or simply exit the program?

c - 如何使用 fread 读取二进制文件?

c++ - 具有两个不同结果的 Rand 函数