【发布时间】:2014-03-05 21:54:03
【问题描述】:
我做了一个申请,你输入所有的分数,它会给你平均分,也会让它重复,但问题是
1) 每当执行“寻找平均值”行时,它都会给我 错误的值,我也使用数组来这样做。
2)每当我尝试 迭代应用程序,调用析构函数并弄乱我的 应用
这是我的代码
#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;
感谢您的宝贵时间
【问题讨论】:
-
'no'不是字符串文字。而again是一个单一的char,因此尝试将其与两个字符进行比较并不是一个好主意。 -
你不应该只通过重复一次(添加所有标记之后)来划分吗?还要注意整数除法。
-
你做错了。难怪你得到错误的价值!
-
您对
'no'的条件检查将不起作用,并且您还有整数除法问题。 -
是的 @Borgleader 帮助我解决了 for 循环问题,但我似乎无法弄清楚 while 循环问题。它不断调用析构函数
标签: c++ arrays class for-loop iterator