C ++ While循环和数组

时间:2014-03-05 21:54:03

标签: c++ arrays class for-loop iterator

我已经创建了一个应用程序,您可以在其中输入所有标记,它会为您提供平均值并使其重复,但问题是

  

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;

感谢您的时间

3 个答案:

答案 0 :(得分:1)

您正在进行整数除法,此外,对于每次迭代,您不会将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;

答案 1 :(得分:0)

std::cin.ignore()会帮助你。

...添加

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

...到while - 循环的最后将清除输入缓冲区直到换行符......你会发现这将结束看似无限的循环。

有关详细信息,请参阅How do I flush the cin buffer?

答案 2 :(得分:0)

由于范围,你的while循环正在调用析构函数。您正在声明运行while循环的每次迭代Grade grd。这意味着前一次迭代中的grd被一次又一次地重新声明,因此析构函数被调用。但那是正常的。您要保存成绩实例吗?在这种情况下,您需要创建一个Grade对象数组