c - 如何显示正确答案的数量?

标签 c while-loop

我正在开始 C 语言编程,并想出了一个简短的测验程序。该程序要求用户输入他们想要回答的问题数量。那么问题的格式相同(# + # + # - #),但每次都会生成随机数。我的问题是如何向用户显示他们在程序结束时获得的正确答案的数量?我知道您必须执行 print f 语句才能显示它,但我不知道还有什么

#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <stdlib.h>
main()
{

srand(time(NULL));

int NumQuestions = 0;
int responce = 0;
int loopcount = 0;
int answer = 0;
int NumCorrect = 0; // HOW TO GET THIS ???????????????????????????????

printf("\n\welcome to your math quize!\n ");

printf("\ntype the numer of questions you would like to answer: ");
scanf("%d", &NumQuestions); //number of questions. 

while(loopcount<NumQuestions){

int n1 = 0;
int n2 = 0; 
int n3 = 0; 
int n4 = 0;
n1 = rand()% 9 + 1;
n2 = rand()% 9 + 1; 
n3 = rand()% 9 + 1; 
n4 = rand()% 9 + 1; 
answer = n1 + n2 + n3 - n4;

              printf("\n%d + %d + %d - %d =", n1, n2, n3, n4);
              scanf("%d", &responce); // user answer

                          if(responce == answer)
                           printf("\ncorrect\n");

                           else
                           printf("\nincorrect\n");

loopcount++;
} //exit loop

printf("you got %d andswers correct!", NumCorrect); //????????????????????????????

getch();
} // end process 

最佳答案

在您的 if 语句中:

 if(responce == answer)
                       printf("\ncorrect\n");

                       else
                       printf("\nincorrect\n");

您应该首先添加大括号并正确格式化它:

 if (responce == answer) {
     printf("\ncorrect\n");
 } else {
     printf("\nincorrect\n");
 }

那么你应该修复英语:

 if (response == answer) {
     printf("\ncorrect\n");
 } else {
     printf("\nincorrect\n");
 }

然后您需要做的就是为正确的情况增加计数器:

 if (response == answer) {
     printf("\ncorrect\n");
     correct_count++;
 } else {
     printf("\nincorrect\n");
 }

另外,请注意,我在这里使用了 Correct_count 而不是 NumCorrect ,因为您的命名应该保持一致;所有其他变量都是小写的,那么为什么选择将 NumCorrect 标题设为大写呢?作为常规编程规则的一部分,一致性非常重要。

关于c - 如何显示正确答案的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4982626/

相关文章:

c - 为什么我的程序输出内存地址?

c - 如何在c中解析小时格式?

linux - 遍历 bash 中的参数

java - [Java]Queue在while循环中,无法修改值?

c - 使用类型双关将对象分解为单词

c - 如何在c中输入/x00内存地址?

c - Gstreamer 编译 - 没有这样的元素或插件 'fakesrc'

python - 简单的 while 循环不会第二次注册 input()

c++ - 在 C++ 中计算连续次数?

c - 我的代码在 C 中看不到 while 循环(使用 getchar 函数)