我遇到了问题,我曾多次尝试解决这个问题,也许你可以提供帮助。 我需要修改下面的程序,以便它要求用户输入除了他们被要求输入数字的次数之外的任何数字。 (即在第一次迭代“请输入0以外的任何数字”和第二次迭代“请输入除1以外的任何数字”等等。当用户输入他们被要求的号码时,程序必须相应地退出现在,我在下面的代码反应有点不同,这就是我运行它时发生的事情:
Enter a number: 4
Please enter a number other than 4
5
Enter a number other than 5
5
wrong
6
Enter a number other than 6
7
Enter a number other than 6
这是我的代码:
#include <stdio.h>
int main()
{
int number, x=0, counter = 0;
printf("Enter a number: ");
scanf("%d", &number);
printf("Please enter a number other than %d\n", number);
while (number!=x)
{
scanf("%d", &x);
while (x!=counter)
{
printf("Enter a number other than %d\n", x);
scanf("%d", &counter);
if (counter==x)
{
printf("wrong\n");
break;
}
}
if (number==x)
{
printf("wrong\n");
break;
}
}
return 0;
}
我真的希望我能正确解释这个问题,请告诉我。
答案 0 :(得分:0)
尝试:
#include <stdio.h>
int main()
{
int number, x=0, counter = 0;
int flag = 0;
printf("Enter a number: ");
scanf("%d", &number);
printf("Please enter a number other than %d\n", number);
while (number!=x)
{
scanf("%d", &x);
while (x!=counter)
{
printf("Enter a number other than %d\n", x);
scanf("%d", &counter);
if (counter==x)
{
printf("wrong\n");
flag = 1;
break;
}
}
if (number==x || flag=1)
{
printf("wrong\n");
break;
}
}
return 0;
}
答案 1 :(得分:0)
如果我理解得很好,你想要一个行为像这样的程序,不是吗?
Please enter a number other than 0
4
Please enter a number other than 1
7
Please enter a number other than 2
8
Please enter a number other than 3
2
Please enter a number other than 4
4
** END OF PROGRAM **
然后,它比你想象的要简单得多......
#include <stdio.h>
int main()
{
int number, counter = 0;
do
{
printf("Please enter a number other than %d\n", counter);
scanf("%d", &number);
}
while (number != counter++);
return 0;
}
更新:
#include <stdio.h>
int main()
{
int number = 0, previous;
do
{
previous = number;
printf("Please enter a number other than %d\n", previous);
scanf("%d", &number);
}
while (number != previous);
return 0;
}