作为练习,我正在做一个小程序,它允许存储多达6个整数偶数,或者如果用户想要完成它,只需输入99,在程序的末尾,它会显示保存的6个数字。
问题是当按下99时,它会按计划显示6个数字的数组,但是数组的最后一个编号(array5)总是99,我找不到发生这种情况的原因。
以下是该程序的代码:
#include <stdio.h>
int main(void)
{
int i; /*integer value*/
int count; /*even values counter defined as 6*/
int array[5] ; /*array where we will save the values*/
int pos = 0; /*array position*/
for (pos = 0; pos < 6; ++pos)
array[pos] = 0;
pos = 0;
for (count = 6 ; count > 0 ; --count)
{
do
{
puts("please write an even integer value or 99 to exit:");
fflush(stdin);
scanf("%d", &i);
if ((i%2) == 0)
array[pos++] = i;
;
} while((i % 2) != 0 && i != 99);
if (i == 99)
count = 0;
}
printf("\n\nThe even integer values you wrote are:\n\n");
for (pos = 0; pos <= 5; ++pos)
printf(" %d ", array[pos]);
return 0;
}发布于 2014-08-27 09:25:14
和@WhozCraig一样,int array[5]不会保存元素的数量,需要更改为int array[6]。
https://stackoverflow.com/questions/25523340
复制相似问题