簡體   English   中英

需要幫助循環魔術數字程序

[英]Need help looping magic-number program

我已經編寫了以下代碼,需要幫助來理解為什么它無法正常工作。 它可以編譯,但是,它不在我的循環中運行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”的輸出,如果他們得分太高,他們應該會看到“ Too High try again !!”的響應,如果他們得分太低,他們應該會看到“ “再次嘗試的次數太低!!此外,它應該顯示出進行了多少次嘗試,以及是否在第一次嘗試中獲得了嘗試。一個人應該能夠進行的最大嘗試次數應該為7 。

問題#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的位置。通過將= (分配)更改為== (比較)來解決此問題。


問題#3和#4在排隊

 else(totalguess >= 2); { 

不知道該如何編譯,但是else if不是, else if應該有一個else while循環一樣,您還有另一個無關的分號。 去掉它。

最后,您只要求用戶輸入一次,因此該程序將循環7次而不要求輸入。 scanf放入主while循環中

根據李維斯的發現,一個解決方案是:

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"); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM