C++估數字

2009-03-23 6:00 am
各位,我正左個c++的估數字game,但係估唔中後唔識叫人重新輸入,應該點攪?


my code:

#include <cstdlib>
#include <iostream>
#include <time.h>

using namespace std;

#define START 1
#define END 100

int main(){

int ans;
int guesstime;
int num;


srand( (unsigned)time(NULL) );
ans = rand() % 100 + 1;
guesstime = 0;


cout << "Please guess a number: \n";
cin >> num;


if (num == ans){
cout << "Congratulations! you use " << guesstime << " time to win it!! \n\n";
}

else if (num > ans){
cout << "Sorry, the number you guess is too large. \n\n" << endl;
}

else if (num < ans){
cout << "Sorry, the number you guess is too small. \n\n" << endl;
}


system("PAUSE");
return 0;
}

回答 (1)

2009-03-23 6:39 am
✔ 最佳答案
You should have used a loop to implement.

#include <cstdlib>
#include <iostream>
#include <time.h>

using namespace std;

#define START 1
#define END 100

int main(){

int ans;
int guesstime;
int num;
int right;


srand( (unsigned)time(NULL) );
ans = rand() % 100 + 1;
guesstime = 0;
right = 0;


right = 0;
while (!right) {
guesstime ++;
cout << "Please guess a number: \n";
cin >> num;
if (num == ans){
cout << "Congratulations! you use " << guesstime << " time to win it!! \n\n";
right = 1;
}

else if (num > ans){
cout << "Sorry, the number you guess is too large. \n\n" << endl;
}

else if (num < ans){
cout << "Sorry, the number you guess is too small. \n\n" << endl;
}

}

system("PAUSE");
return 0;
}


收錄日期: 2021-04-30 13:00:02
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090322000051KK01981

檢視 Wayback Machine 備份