考试成绩平均值和没有指针的A,B,C,D,F成绩的学生人数

test score average and number of students with A,B,C,D,F grade without pointer

本文关键字:平均值 考试 指针      更新时间:2023-10-16

我正在尝试在不使用指针的情况下制作一个C++程序来计算A,B,C,D,F等级的数量。我以为这很容易,但仍然有问题。我的代码正确计算了 C、D、F 等级的数量,但每当我输入 A(90-100( 和 B(80-89( 分数时,它都会显示奇怪的数字,例如 907517809。为什么会这样工作?它正确计算平均分数。这可能是一个基本问题,但我很好奇。提前抱歉。

#include <iostream>
using namespace std;
int main(){
int i,testscore,N;
int sum=0;
int Acount,Bcount,Ccount,Dcount,Fcount=0;
std::cout<<"How many test scores? " <<endl;
cin>> N;
    if(N<1){
    std::cout<<"Invalid input. try again"<<endl;
    }
    else if(N>25)
    {
    std::cout<<"1-25 only."<<endl;    
    }
    else if(N>0 && N<25){
    std::cout<<"Total number of test is: "<< N << endl;      
    }
for(i = 0; i < N; i++)
    {
        cout << "Enter the score of students " << i + 1 << ": "; 
        cin >>testscore;
        if(testscore >= 90 && testscore < 100){
        Acount++;
        }
        else if(testscore >= 80 && testscore < 90){
        Bcount++;
        }
        else if(testscore >= 70 && testscore < 80){
        Ccount++;
        }
        else if(testscore >= 60 && testscore < 70){
        Dcount++;
        }
        else if(testscore <60){
        Fcount++;
        }
        sum+=testscore;
    }

std::cout<<"The average test score is: "<<sum/N<<endl;
std::cout<<"The number of A grades: " <<Acount<<endl;
std::cout<<"The number of B grades: " <<Bcount<<endl;
std::cout<<"The number of C grades: " <<Ccount<<endl;
std::cout<<"The number of D grades: " <<Dcount<<endl;
std::cout<<"The number of F grades: " <<Fcount<<endl;
    return 0;
}

因为你只将 Fcount 初始化为零。 您还需要分配所有其他内容。

int Acount=0,Bcount=0,Ccount=0,Dcount=0,Fcount=0;

您可能已经知道,如果没有此赋值,变量将具有随机数。

您应该会收到有关使用未初始化值的警告。 最好尽可能以最严格的模式进行编译。 这样做将有助于避免这些琐碎但耗时的错误。