任何人都可以告诉我,为什么我的代码工作正常,直到我到最后的不足,我问用户他们是否想再次玩?出于某种原因,该程序似乎忽略了这一行代码。请尽量温柔,因为我是编程新手,并试图自学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