【问题标题】:Percent of correct answers program challenge正确答案计划挑战的百分比
【发布时间】:2015-04-18 00:13:57
【问题描述】:

我的程序输出有问题,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;
}

【问题讨论】:

  • TL;博士。听起来像是整数除法问题。整数除法不产生余数或小数。在除法之前转换为浮点数。
  • 可以使用浮点数吗?
  • 是的,我只是没有意识到我必须转换它,因为每个人都告诉我。谢谢大家

标签: c++ percentage


【解决方案1】:

除满分外,整数除法将产生 0。改为使用浮点除法:

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

请注意,(double)(20-count) 将值 (20-count) 转换为双精度浮点数。计算完整个表达式后,它会被强制转换为整数,因为您将值分配给 int

【讨论】:

  • OHHHH,有道理!谢谢先生。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    int percent = 5 * ( 20 - count );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-06
      • 2017-11-03
      • 1970-01-01
      • 2018-07-15
      • 2021-02-02
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多