有人能给我提示为什么这不打印数组吗?我不知道我的打印功能出了什么问题。在将其他部分添加到代码中之前,我想确保它正常工作。我猜我没有正确设置数组,这就是为什么没有打印出任何内容。
#define NUMSTU 50
#include <stdio.h>
//function prototype
void printdata();
//Global variables
int stuID[NUMSTU];
int stuCount;
int totStu;
int main ()
{
int stuCount = 0;
int totStu = 0;
int studentID;
//Prompt user for number of student's in class
printf("Please enter number of student's in class:");
scanf ("%d", &totStu);
for (stuCount = 0; stuCount <totStu; stuCount++)
{
//Prompt user for student ID number
printf("\n Please enter student's ID number:");
scanf("%d", &studentID);
stuID[NUMSTU] = studentID;
}
//Call Function to print data
printdata();
return 0;
}//end main
void printdata(){
//This function will display collected data
//Input: Globals stuID[NUMSTU]
//Output: none
//Display column headers
printf("\n\n stuID\n");
//loop and display student ID numbers
for (stuCount = 0; stuCount <totStu; stuCount++){
printf("%d", stuID);
}
}
最佳答案
你这里有不止一个错误。 首先,你应该因为这一行而得到一个越界异常 (使用高级编程语言):
stuId[NUMSTU] = studentId;
stuId
是一个初始长度为 NUMSTU
的数组。
您尝试在 NUMSTU
中访问它,即使它具有可访问的插槽
仅在 0
和 (NUMSTU-1)
之间。
您可能想做这件事:
stuId[stuCount] = studentId;
并且在打印中,您只是再次打印数组的位置 然后再次。而不是:
print("%d", stuId);
做:
print("%d", stuId[stuCount]);
哦,是的,还有第三个错误:
int stuCount = 0;
int totStu = 0;
stuCount
和 totStu
已声明为全局变量
(意味着每个函数都可以访问它们)。
您正在做的是定义具有相同名称的新变量,
但不能被其他函数访问。
因此,您应该决定它们是全局性的还是本地性的。
无论如何,你应该将其更改为:
stuCount = 0;
totStu = 0;
现在应该可以工作了。
关于c - 打印用户输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833672/