程序挑战的正确答案百分比

Percent of correct answers program challenge

本文关键字:答案 百分比 挑战 程序      更新时间:2023-10-16

我的程序输出有问题,txt文件显示学生答错了3个答案,但它一直给我0%的正确答案。

我面临的挑战是:

"你的一位教授让你写一个程序来给她的期末考试打分,只有20道选择题。每个问题都有四个可能的答案之一:A、B、C或D。文件CorrectAnswers.txt包含所有的问题,每个答案都写在一行。第一行包含第一个问题的答案,第二行包含第二个问题的回答,依此类推。编写一个程序,将CorrectAnswers.txt文件的内容读取为字符数组,然后将包含学生答案的另一个文件的内容读入第二个字符数组。

该程序应确定学生错过,然后显示以下内容:

•学生遗漏的问题列表,显示正确答案和学生为每个遗漏的问题提供的错误答案

•遗漏的问题总数

•正确回答问题的百分比。这可以计算为正确回答的问题÷问题总数

•如果正确回答问题的百分比为70%或更高,则该程序应表明该学生通过了考试。否则,应表明学生考试不及格

这是我到目前为止的代码,提前感谢您的任何建议!

#include <iostream> 
#include <fstream>
#include <string> 
using namespace std;
int main()
{
const int size=20;
static int count=0;
string correctAnswers[size];
string studentAnswers[size];
ifstream inFileC;
inFileC.open("c:/Users/levi and kristin/Desktop/CorrectAnswers.txt");
if (inFileC)
{
for (int i=0;i<20;i++)
{
inFileC>>correctAnswers[i];
}
}
else
{
cout<<"Unable to open "CorrectAnswers.txt""<<endl;
cout<<"Please check file location and try again."<<endl<<endl;
}
inFileC.close();
ifstream inFileS;
inFileS.open("c:/Users/levi and kristin/Desktop/StudentAnswers.txt");
if (inFileS)
{
for (int t=0;t<20;t++)
{
inFileS>>studentAnswers[t];
}
}
else
{
cout<<"Unable to open "StudentAnswers.txt""<<endl;
cout<<"Please check file location and try again."<<endl<<endl;
}
inFileS.close();
for (int k=0;k<20;k++)
{
if (correctAnswers[k]!=studentAnswers[k])
{
cout<<endl<<"Correct Answer: "<<correctAnswers[k];
cout<<endl<<"Student Answer: "<<studentAnswers[k]<<endl;
count++;
}
}
int percent=((20-count)/20)*100;
cout<<endl<<"Number of missed questions: "<<count;
cout<<endl<<"Percent of correctly answered questions: "<<percent<<"%";
if (percent>=70)
{
cout<<endl<<endl<<"********"<<endl<<"**Pass**"<<endl<<"********"<<endl<<endl;
}
else
{
cout<<endl<<endl<<"********"<<endl<<"**Fail**"<<endl<<"********"<<endl<<endl;
}
return 0;
}

整数除法除完美分数外,所有结果都为0。改用浮点除法:

int percent = ((double)(20-count) / 20) * 100;

请注意,(double)(20-count)将值(20-count)强制转换为双精度浮点数。一旦对整个表达式求值,它就会被强制返回为一个整数,因为您要将值赋给int

整数除法总是向零取整,因此如果count大于0,则(20 - count)/20将为零。

不需要浮点,这就可以了:

int percent = 5 * ( 20 - count );