我尝试在代码块上制作一个简单的程序,该程序最多可获取50个数字并将其放入数组中。如果您输入-1或0,它将停止。此后,它会打印出您输入的所有数字。
代码块表示一切正确,没有错误。当我运行该程序时,什么都没有出现:屏幕为黑色。
int main()
{
int i;
int usernumbers[i];
const N = 50;
printf("write an integer (-1 or 0 to stop)\n");
scanf("%d", usernumbers[i]);
while(usernumbers[i] != -1 && usernumbers[i] != 0){
for( i=0; i<N; i++){
printf("Next number: \n");
scanf("%d", usernumbers[i]);
}
}
printf("The numbers you entered are: \n");
for(i=0; i<N; i++){
printf("%d", usernumbers[i]);
}
return 0;
}
进程返回-1073741571(0xC00000FD)
答案 0 :(得分:0)
始终在使用前初始化var。
int main(int argc, char* argv[])
{
const int N = 50;
// initialize your array with zero's
int userNumbers[N] = { 0 };
printf("write an integer (-1 or 0 to stop)\n");
// initialize the var with 0.
int index = 0;
// in this case I don't initialize because I will initialize below, on scanf_s
int number;
// Check against scanf_s result and if index is less then N, we don't want index out of bounds
while (scanf_s("%d", &number) && index < N)
{
// the numbers you defined to stop
if (number == -1 || number == 0)
break;
// put the number into array and add 1 to index
userNumbers[index++] = number;
}
printf("The numbers you entered are: \n");
for (int i = 0; i < N; i++)
{
printf("%d\n", userNumbers[i]);
}
return 0;
}
唯一的不同是循环。没道理您有一个while
,其中包含for。您的while
将运行一次,而您的for
将运行N次,因此请检查输入的数字是否为-1或0将不会得到预期的处理。
答案 1 :(得分:0)
以下建议的代码:
usernumbers[]
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#define N 50
int main( void )
{
int usernumbers[ N ] = {0};
printf("write an integer (-1 or 0 to stop)\n");
for( int i = 0; i < N; i++ )
{
if( scanf( "%d", &usernumbers[i] ) != 1 )
{
fprintf( stderr, "scanf failed to read number\n" );
exit( EXIT_FAILURE );
}
if( usernumbers[i] == -1 || usernumbers[i] == 0)
{
break;
}
printf("Next number: \n");
}
printf("The numbers you entered are: \n");
for( int i=0; i<N; i++ )
{
if( usernumbers[i] == -1 || usernumbers[i] == 0 )
{
break;
}
printf( "%d ", usernumbers[i] );
}
return 0;
}
答案 2 :(得分:-1)
usernumbers
的定义是错误的。
我也很惊讶const N = 50;
行没有触发编译器错误。
您应该执行以下操作:
#define N 50
int usernumbers[N];