我正在为C类介绍制作一个加法/乘法游戏。该程序的目标是询问用户,您想要使用的最大数量是什么,它将在该最大范围内播种随机数以及您想要做多少个不同的问题。当我运行程序并进行数学计算时,它告诉我总和不正确,并为我提供了一个不正确的答案,通常是一个很大的数字,如“1254323”。你能指出我在做错的方向吗?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int maxNumber, num1, num2, sum, answer, problems, i;
srand(time(NULL));
//printf("Would you like 1)Addition or 2)Multiplication?\n")
printf("Enter your Max Number:");
scanf("%d", &maxNumber);
printf("How many problems do you want?\n");
scanf("%d", &problems);
sum = num1 + num2;
while(i != problems) {
num1 = rand()%maxNumber;
num2 = rand()%maxNumber;
i++;
printf("What is %d + %d\n",num1, num2);
scanf("%d", &answer);
if(answer != sum){
printf("Sorry, that's incorrect, the answer is %d\n", sum);
}
else{
printf("Correct!\n");
}
}
return 0;
}
答案 0 :(得分:1)
您在设置sum
和num1
之前指定了num2
。
将sum = num1 + num2;
行移到num2 = rand()%maxNumber;
行之后的循环中,它应该可以正常工作。
还有一些其他错误(例如将i
初始化为0)。
for
循环代替while
循环通常被认为是更好的做法。
这里有更易读的代码
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int maxNumber, num1, num2, sum, answer, problems, i;
srand(time(NULL));
printf("Enter your Max Number:");
scanf("%d", &maxNumber);
printf("How many problems do you want?\n");
scanf("%d", &problems);
for (i = 0; i < problems; i++) {
num1 = rand()%maxNumber;
num2 = rand()%maxNumber;
sum = num1 + num2;
printf("What is %d + %d\n",num1, num2);
scanf("%d", &answer);
if(answer != sum){
printf("Sorry, that's incorrect, the answer is %d\n", sum);
} else {
printf("Correct!\n");
}
}
return 0;
}
答案 1 :(得分:1)
您正在使用变量而不初始化它们。变化:
int maxNumber, num1, num2, sum, answer, problems, i;
要:
int maxNumber = 0, num1 = 0, num2 = 0, sum = 0, answer = 0, problems = 0, i = 0;
另外,将sum = num1 + num2;
行移至您创建num1
和num2
的位置之后。
答案 2 :(得分:0)
您的程序存在多个问题,包括格式化。以下是更正:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int maxNumber, num1, num2, sum, answer, problems, i;
srand(time(NULL));
//printf("Would you like 1)Addition or 2)Multiplication?\n")
printf("Enter your Max Number:");
scanf("%d", &maxNumber);
printf("How many problems do you want?\n");
scanf("%d", &problems);
// issue: i was not initialized
i = 0;
while(i != problems){
i++;
num1 = rand()%maxNumber;
num2 = rand()%maxNumber;
printf("What is %d + %d\n", num1, num2);
// issue: sum was not calculated here
sum = num1 + num2;
scanf("%d", &answer);
if(answer != sum){
printf("Sorry, that's incorrect, the answer is %d\n", sum);
}
else{
printf("Correct!\n");
}
}
return 0;
}
答案 3 :(得分:0)
定义sum = num1 + num2,其中num1和num2根本没有分配。 C默认情况下不会将数字初始化为零。这就是为什么你有这么大的数字。
只需在sum = num1 + num2
之后添加num2 = rand()%maxNumber;
即可,一切正常!