主要要点是我想在答案为“ y”时向数组添加数字。当我输入1 2 3 4 5 6时,它只将最后3个数字加到数组上(所以是4 5 6),有时甚至跳过字符扫描。
代码如下:
int numbers1[99];
int i;
int n = 0;
char answer = 'y'
while (answer == 'y')
{
n += 1;
for (i = 0; i < n; i++)
{
printf("Insert a number: ");
scanf("%d", &numbers1[i]);
printf("Would you like to add more numbers? [Y/N]");
scanf(" %c", &answer);
}
}
printf("Numbers are following: ");
for (i = 0; i < n; i++)
{
printf("%d, ", numbers1[i]);
}
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
您只需要一个循环。将您的代码更改为
while (answer == 'y' && n < 99) //check also for the array bound.
{
printf("Insert a number: ");
scanf("%d", &numbers1[n++]); //use 'n' as counter and increment it
printf("Would you like to add more numbers? [Y/N]");
scanf(" %c", &answer);
}
注意:错误检查留给用户实施。
答案 1 :(得分:0)
其中一个循环是多余的。也就是说,for
循环在while
循环的上下文中没有意义。
请考虑到您要求用户在提示中输入'Y'
或'N'
,但将变量answer
与字符'y'
进行比较。
我可以提出以下解决方案。
#include <stdio.h>
#include <ctype.h>
int main( void )
{
enum { N = 99 };
int numbers1[N];
int n = 0;
for ( char answer = 'Y'; n < N && answer == 'Y'; n++ )
{
printf("Insert a number: ");
scanf("%d", &numbers1[n]);
printf("Would you like to add more numbers? [Y/N] ");
if ( scanf( " %c", &answer ) != 1 ) answer = 'N';
answer = toupper( ( unsigned char )answer );
}
printf( "\nNumbers are following: " );
for ( int i = 0; i < n; i++ )
{
if ( i != 0 ) printf( ", " );
printf( "%d", numbers1[i] );
}
putchar( '\n' );
}
程序输出看起来像
Insert a number: 0
Would you like to add more numbers? [Y/N] y
Insert a number: 1
Would you like to add more numbers? [Y/N] 1
Insert a number: 2
Would you like to add more numbers? [Y/N] y
Insert a number: 3
Would you like to add more numbers? [Y/N] y
Insert a number: 4
Would you like to add more numbers? [Y/N] y
Insert a number: 5
Would you like to add more numbers? [Y/N] y
Insert a number: 6
Would you like to add more numbers? [Y/N] y
Insert a number: 7
Would you like to add more numbers? [Y/N] y
Insert a number: 8
Would you like to add more numbers? [Y/N] y
Insert a number: 9
Would you like to add more numbers? [Y/N] n
Numbers are following: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9