#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times ;
}
printf("FAILURE!");
return 0;
}
任務的重點是制作一個程式,讓用戶輸入并嘗試通過 8 次嘗試猜測 1-300 之間的數字。如果您找到數字,它顯示正確!如果不是,它會通過告訴您數字更大/更小來指導您。如果您在 8 次嘗試中失敗,則表明失敗。問題在于,當您在 8 次嘗試中未能猜出時,它會顯示失敗,但是當您找到數字時,它會同時列印 RIGHT 和 FAILURE。僅當您在 8 次嘗試中找不到數字時,我應該如何糾正程式列印失敗?
uj5u.com熱心網友回復:
我的 2 美分,阻力最小的路徑是簡單的return而不是break用戶正確猜測時:
if (num == rnum)
{
printf("RIGHT!");
return 0; // program exits here, no FAILURE print
}
您還應該rand使用不斷變化的數字(例如時間)為該函式設定種子。使用常數,您會發現每次要猜測的數字都相同。
srand(time(NULL)); // randomize seed
uj5u.com熱心網友回復:
在執行列印陳述句之前,您應該檢查它們是否超過 8 次嘗試限制:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times ;
}
if (times > 8)
{
printf("FAILURE!");
}
return 0;
}
uj5u.com熱心網友回復:
我認為你應該寫return 0; 而不是休息;正確列印后。因為如果你猜 rnum 它將列印 RIGHT 并爆發,然后它也會列印 FAILURE 但如果你寫 return 0; 它將結束程式。
uj5u.com熱心網友回復:
當您break;列印完后出去時,RIGHT!您最終會到達列印位置,FAILURE!因此您需要以某種方式進行檢查。
這是我的看法:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num = 0, rnum;
// This game will get boring with a static seed.
// I'm assuming you use this seed for testing only.
srand(4383);
rnum = rand() % 300 1;
for(int times = 0; times < 8; times) { // simpler loop
printf("Guess the random number between 1-300: ");
// if the user fails to enter a number - make it print FAILURE
if(scanf("%d", &num) != 1) break;
if(num < rnum)
puts("The random number is bigger");
else if(num > rnum) // added "else"
puts("The magic number is smaller");
else
break; // neither less nor greater than rnum so it must be correct
}
if(num == rnum) // added check
printf("RIGHT!\n");
else
printf("FAILURE!\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364678.html
標籤:C
上一篇:For回圈中的多個printf作為初始化、條件和更新的一部分
下一篇:memset對浮點陣列做了什么?
