我正在研究一个编码问题“从输入中找到最小的数字”,我以 for 循环的形式获取输入并将它们存储在数组中。对于总输入数小于 11 的情况,它工作正常,但对于大于 11 的输入,它只需要 10 个输入,然后就会中断。
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size , var1;
scanf("%d",&array_size );
var1 = array_size;
int index = 0 , array[index];
for(int index = 0; index < array_size; index++)
{
printf("inputs left: %d\n",var1);
var1 -= 1;
scanf("%d",&array[index]);
}
我预计它应该根据用户的需要接受尽可能多的输入,但它只需要 10 个输入,而且我似乎找不到问题。
最佳答案
您想要创建一个大小为零的数组,这是不允许的。您也无法声明具有可变大小的数组,因此您必须使用malloc
或其他东西。
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size;
scanf("%d", &array_size);
int* Array = (int *) malloc(array_size * sizeof(int));
for(int index = 0; index < array_size; index++)
{
printf("inputs left: %d\n", array_size - index);
scanf("%d", (Array + index));
}
for(int i = 0; i < array_size; i++)
{
printf("%d\n\r", *(Array + i));
}
free(Array);
return 0;
}
这给出
HOW MANY NUMBERS DO YOU WANT TO INPUT
3
inputs left: 3
1
inputs left: 2
2
inputs left: 1
3
1
2
3
或者你使用类似 std::vector
的东西。
#include <stdio.h>
#include <vector>
int main()
{
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size;
scanf("%d", &array_size);
std::vector<int> Array;
for(int index = 0; index < array_size; index++)
{
int Temp;
printf("inputs left: %d\n", array_size - index);
scanf("%d", &Temp);
Array.push_back(Temp);
}
for(int i = 0; i < array_size; i++)
{
printf("%d\n\r", Array.at(i));
}
return 0;
}
这会产生相同的输出。
关于c - For 循环无法正常工作以获取 c 中数组中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461447/