我已经编写了下面的代码,需要帮助理解为什么它不按预期的方式工作。但是,它编译时,它不会在我的循环中运行if-else。例如,如果我在我的代码中取出while循环,一切都会正常工作,但是,我想知道在这种情况下有人猜测“神奇数字”或随机数需要多少次尝试。
#include <stdio.h>
int main()
{
int magicnum = 1234;
int userguess;
int totalguess = 0;
printf("Try to guess a number between 1 and 10000!: ");
scanf("%d", &userguess);
while(totalguess <= 7 && magicnum != userguess);{
if(magicnum == userguess){
printf("Congratulations, You Win!!\n");
if(totalguess = 1){
printf("Wow you did it on your first try!!\n");
}
else(totalguess >= 2); {
printf("Nice one!! It only took you %d tries!\n", totalguess);
}
}
else if(magicnum > userguess){
printf("Too Low try again!!\n");
}
else{
printf("Too High try again!!\n");
}
totalguess++;
}
return 0;
}
我正在寻找任何一个回答正确数字的人的输出“1234”,如果他们得分太高他们应该看到“太高再试!!”的反应,如果得分太低他们应该看到“太低的反应再试一次!!。此外,它应该显示它花了多少次尝试,如果他们在第一次尝试时得到它。一个人应该能够做到这一点的最大尝试次数应该是7。
答案 0 :(得分:4)
问题#1问题在于
行while(totalguess <= 7 && magicnum != userguess);{
特别是在分号处。以上评估如下
// Sit on this line until a condition is met
while(totalguess <= 7 && magicnum != userguess);
// Some block of code which is unrelated to the while loop
{
...
}
答案是在while循环结束时删除无关的分号:
while(totalguess <= 7 && magicnum != userguess) {
// No semicolon ^
<小时/> 问题#2在
行中
if (totalguess = 1){
您实际上将totalguess指定为1.通过将=
(赋值)更改为==
(比较)来解决此问题。
行中
else(totalguess >= 2); {
不确定这是如何编译的,但你应该有else if
而不是else
。和while
循环一样,你有另一个无关的分号。删除它。
最后,您只需要输入一次用户输入,因此程序将循环7次而不需要输入。将您的scanf
置于主while
循环
答案 1 :(得分:0)
根据Levi的调查结果,解决方案:
const int magic_num = 1234;
const uint max_num_guess = 7;
uint num_guess = 1 + max_num_guess;
int user_guess;
printf( "Try to guess a number between 1 and 10000!\n" );
for( uint idx = 0; idx < max_num_guess; ++idx )
{
scanf( "%d", &user_guess );
if( magic_num == user_guess ) { num_guess = 1 + idx; idx = max_num_guess; }
else
{
if( magic_num < user_guess ) { printf( "Too High try again!!\n" ); }
else { printf( "Too Low try again!!\n" ); }
}
}
if( num_guess <= max_num_guess )
{
printf( "Congratulations, You Win!!\n" );
if( 1 == num_guess ) { printf( "Wow did it on your first try!!\n" ); }
else { printf( "Nice one!! %d tries!\n", num_guess ); }
}
到#3它是有效的。考虑:
if(false){}
else(printf("Branch!\n"));
{ printf("Done.\n"); }