我正在编写一个程序,要求用户提供姓名和 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/