Visual C ++中的奇怪输出

时间:2012-02-08 11:56:53

标签: c++

以下是代码:

// WAP to implement student result preparation.

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

float total;
const int obj = 3;
const int size = 3;

class student
{
    int rollno;
    char name[20], grade;
    float marks[size], perc;
public:
    void getval()
    {
        cout << "Enter roll number: ";
        cin >> rollno;
        cout << "\nEnter student's name: ";
        cin >> name;
        cout << "\nEnter student's physics marks: ";
        cin >> marks[0];
        cout << "\nEnter student's chemistry marks: ";
        cin >> marks[1];
        cout << "\nEnter student's mathematics' marks: ";
        cin >> marks [2];
        cout << "\n";
    }
    void calculate()
    {
        perc = total / 3;
        if (perc < 50)
            grade = 'F';
        else if (perc >=50 && perc < 60)
            grade = 'D';
        else if (perc >= 60 && perc < 75)
            grade = 'C';
        else if (perc >= 75 && perc < 90)
            grade = 'B';
        else
            grade = 'A';
    }
    void prnresult()
    {
        cout << "\nRoll number: " << rollno;
        cout << "\nName: " << name;
        cout << "\nTotal marks: " << total;
        cout << "\nPercentage: " << perc;
        cout << "\nGrade: " << grade;
        cout << "\n";
    }
};

student jk[obj];

int _tmain(int argc, _TCHAR* argv[])
{   
    for (int i = 0; i < obj; i++)
    {   cout << "Student " << i + 1 << "\n";
        jk[i].getval();
    }
    for (int j = 0; j < obj; j++)
    {
        jk[j].calculate();
        cout << "Result: ";
        jk[j].prnresult();
    }
    _getch();
    return 0;
}

这是一本教科书计划。作者说它在Turbo C ++中完美运行(你能想象吗?在20世纪90年代早期最新更新的东西!)。但是当我在Visual C ++ 2010 Express中编译它时,它不会计算总数和百分比。它只显示零。知道为什么会这样吗?

2 个答案:

答案 0 :(得分:3)

作者说谎。我在代码中找不到任何赋值给total变量的地方。因此,total值仍为0(全局变量的0初始化)。因此,perc = total / 3;也等于0

答案 1 :(得分:1)

“total”永远不会被初始化(或修改)。