C语言 读取整数数组并打印出来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4537113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading an array of integers and printing them out
提问by Ordo
I'm learning C on my own and doing a few exercises.
The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output.
When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
我正在自己学习 C 并做一些练习。
以下代码从用户读取整数数组。当用户键入“0”或填充数组时,将打印出整数。现在的问题是输出。
当我在输入 3 位数字(例如 1 2 3)后输入“0”时,输出如下:1 2 3 -858993460 -858993460。我不确定为什么我得到值“-858993460”,但我已经找到了避免它的解决方案。现在我的问题是这些值的含义,以及是否有比我更智能的解决方案,如下面的评论所示。
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
采纳答案by codaddict
This happens because irrespective of when the 0input is given you print all 5numbers:
发生这种情况是因为无论何时0给出输入,您都会打印所有5数字:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0by running a loop from 0to i:
要解决此问题,您可以0通过从0to运行循环来仅打印用户在输入 a 之前输入的数字i:
for (int j =0; j < i; j++ )
回答by Falmarri
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
这 2 个数字是数组最后 2 部分的内存位置中留下的垃圾。当你只输入 3 个数字时,你永远不会初始化它们,所以当你遍历并打印数组中的所有 5 个元素时,它会打印内存中的任何垃圾。
回答by DReJ
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int));to set initials values in array to 0.
您打印数组中的所有整数,其大小为 arraylength = 5。因此您在输出中得到 5 个整数。由于您没有初始化数组,因此您将获得未初始化的值作为数组的第 4 和第 5 个元素。您可以使用memset(&input, 0, arraylength*sizeof(int));将数组中的初始值设置为 0。

