【发布时间】:2013-10-14 21:23:01
【问题描述】:
我刚刚开始我的编程入门课程(所以请多多包涵),但我有点卡在第一个作业上。
我应该编写一个数字猜谜游戏,将 1 到 10 之间的随机数存储到一个变量中,提示用户输入一个数字,并通知用户是否猜到了相同的数字。
我已经搞砸了一段时间了,代码与我开始时的代码相比发生了很大变化。目前,无论我猜如何,该程序都在说“恭喜,你是赢家”......
如果有人能指出我做错的方向,那就太好了。
自最初发布问题以来,代码已被编辑
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Declare Variables
int RandomNum;
int UserGuess;
//Initialize Variables
RandomNum=0;
srand ( (unsigned)time ( NULL ) );
char UserInput = 'a';
int a = UserInput;
//Generate RandomNum
RandomNum = (rand() % 10)+1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
【问题讨论】:
-
这个
UserGuess=atoi("UserInput");很糟糕,需要删除。这个scanf("%d", &UserInput);试图将int读入char,这也不是好消息。 -
您仍在尝试将
int填充到char中。将char UserInput = 'a'; int a = UserInput;更改为int Userinput = 0;。你不会使用a来做任何事情,所以别管它了。删除UserGuess,因为你不使用它。
标签: c if-statement random