gpt4 book ai didi

C++ While 循环和数组

转载 作者:行者123 更新时间:2023-11-28 07:02:39 27 4
gpt4 key购买 nike

我制作了一个应用程序,您可以在其中输入所有分数,它会为您提供平均值并使其重复出现,但问题是

1) when ever the 'Finding average' line is executed, it gives me the wrong value and also I use array to do so.

2)When ever I try to iterate the application, the destructor is called and messes up my application

这是我的代码

#include <iostream>
#include <string>
using namespace std;

class Grade{
private:
int* ptr;
int number;
public:
Grade(const int hNumber){
number = hNumber;
ptr = new int[this->number];
}
Grade(const Grade& cpy){
ptr = new int[cpy.number];
}
void get_marks(){
for(int i = 0; i < number; ++i){
cout << "Enter Mark " << i << ": ";
cin >> ptr[i];
}
}
const int& operator [](const int access) const{
return ptr[access];
}
~Grade(){
cout << "Deleting memory" << endl;
delete [] ptr;
}
};

int main(){
//local variables
int sum = 0;
string name,subject;
int repeat;
char again = 'y';
//user interface
cout << "Welcome to Grade Marker" << endl;
cout << "Enter your name: ";
getline(cin,name);
while(again == 'y'){
cout << "Enter the subject name: ";
getline(cin,subject);
cout << "How many marks are being entered: ";
cin >> repeat;
//creating instance of grade
Grade grd(repeat);
grd.get_marks();;
//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;
//looping the application
cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}
system("pause");
return 0;
}

为了简单起见,我认为给我错误的代码部分是

cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}

//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;

谢谢你的时间

最佳答案

您正在进行整数除法,此外您没有为每次迭代将 sum 重新初始化为 0。您可以在循环内移动 sum 声明并只写:

float sum = 0;
for (int i = 0; i < repeat; i++){
sum += grd[i];
}
cout << "The average mark is: ";
cout << sum / repeat << endl;

关于C++ While 循环和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210171/

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