任何人都可以告訴我,爲什麼我的代碼工作正常,直到我到最後的不足,我問用戶他們是否想再次玩?出於某種原因,該程序似乎忽略了這一行代碼。請儘量溫柔,因爲我是編程新手,並試圖自學Objective-C。這個程序對於noobs是典型的,我產生一個隨機數字,要求用戶猜測,然後詢問他們是否想再次玩。謝謝。爲什麼我的最終scanf停止並閱讀用戶輸入?
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
int randomNumber = arc4random_uniform(100); // This is a random number generator that gens a num betw 0 and 100
int userNumber; // This is the number that the user picks intially
int attempts = 0; // This is the number of attempts the user makes during each game
int games = 0; // This is the number of games the user has played
char play = 'n'; // This is whether the user wants to play again, intially set to 'y'
scanf("%c", &play);
while (play == 'y') {
NSLog(@"Random number is: %d", randomNumber);
NSLog(@"Enter a number between 0 and 100");
scanf("%d", &userNumber);
games++; // Increment the number of games the user has played to 1
if (userNumber == randomNumber) {
attempts++;
NSLog(@"Congratulations. You guessed correctly!");
}
attempts++;
while (userNumber != randomNumber) {
if (userNumber < randomNumber) { // Guess is too low
attempts++; // attempt is incremented
NSLog(@"Too low. Try again!"); // User tries again
scanf("%d", &userNumber);
}
if (userNumber > randomNumber) { // Guess is too high
attempts++; // attempt is incremented
NSLog(@"Too high. Try again!"); // User tries again
scanf("%d", &userNumber);
}
}
NSLog(@"Congratulations. You guessed correctly!");
NSLog(@"It took you %d attempts to guess correctly", attempts);
NSLog(@"Do you want to play again?");
scanf("%c", &play); // --------- Here is where things to wrong ---------
} // while play is yes
} // autoreleasepool
return 0;
} // main
這真的沒有任何用Objective-C做什麼;當'printf'執行相同操作時,你正在使用'NSLog'。可能值得作爲一個簡單的C問題重新標記。 – 2013-04-20 21:46:04
可能最後的'scanf()'讀取換行符並繼續(數字不讀取換行符)。也許在'%c'之前放一個空格:'scanf(「%c」,&play);'。檢查'scanf()'的返回值,甚至可能檢查讀取的字符 – 2013-04-20 21:55:46
%c如何做到這一點?我認爲它是讀取/ n字符而不是我想要它讀取的內容,它是'y'或'n'。就我的理解而言,%d整數沒有閱讀換行符,但是%c的確是這樣的嗎?是否正確?防止這種情況的方法是使用空格嗎?我只是不明白我會怎麼做到這一點。謝謝。 – 2013-04-20 22:24:02