gpt4 book ai didi

c++ - C++数学测验的输出累加器

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:21 28 4
gpt4 key购买 nike

好的,我正在创建一个数学测验。现在只是一些基本的东西,但在我的 while 循环结束时我想累积输出,这意味着如果你做 5 个加法问题,输出将存储所有 5 个问题的表达式并使用条件运算符来判断答案是否是对还是错,会在最后显示。

我在 Java 中有相同的程序,但我想将它切换到 C++,因为我真的很喜欢 C++,并且想要更多,这就是为什么我想解决这个问题。

Java:

output += "\n" + number1 + " - " + number2 + " = " + answer + ((number1 - number2 == answer) ? " CORRECT" : " WRONG");

我的 while 循环 w/C++ 中的输出累加器:

while (count <= NUMBER_OF_QUESTIONS) {

num1 = 1 + rand() % 50;
num2 = 1 + rand() % 50;

if (num1 < num2) {
temp = num2;
num2 = num1;
num1 = temp;
}

cout << "\n"<< num1 << " + " << num2 << " = " << endl;
cin >> answer;

if (num1 + num2 == answer) {
cout << "Right!" << endl;
correctCount++;
}
else
cout << "Wrong! Should be " << (num1 + num2) << endl;

// Increase count
count++;

// Prepare all questions if correct or wrong, for output
output += // The rest...
}

//and for final output

cout << output;

最佳答案

不使用任何 STL 库:只需将您的变量存储在一个数组中。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>


#define NUMBER_OF_QUESTIONS 5

int main()
{
srand ( time(NULL) );
int count = 0;
//Init a
int output[NUMBER_OF_QUESTIONS][4];

while (count <= NUMBER_OF_QUESTIONS) {

int num1 = 1 + rand() % 50;
int num2 = 1 + rand() % 50;
int answer = 0;

if (num1 < num2) {
int temp = num2;
num2 = num1;
num1 = temp;
}

std::cout << "\n"<< num1 << " + " << num2 << " = " << std::endl;
std::cin >> answer;

if (num1 + num2 == answer) {
std::cout << "Right!" << std::endl;
//correctCount++;
}
else
{
std::cout << "Wrong! Should be " << (num1 + num2) << std::endl;
}

// Prepare all questions if correct or wrong, for output
output[count][0] = num1;
output[count][1] = num2;
output[count][2] = answer;
output[count][3] = (num1 + num2 == answer);

// Increase count
count++;
}
for (int i =0; i < NUMBER_OF_QUESTIONS; i++)
{
std::cout << "Q" << i << " : " ;
std::cout << output[i][0] << " + " << output[i][1];
std::cout << " = " << output[i][2] << " . ";
if (output[i][3])
std::cout << "Right Answer ! " << std::endl;
else
std::cout << "Wrong! Should be " << (output[i][0] + output[i][1]) << std::endl;

}
}

关于c++ - C++数学测验的输出累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13583537/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com