可变百分比显示零值

时间:2016-11-25 18:10:10

标签: c++

嘿伙计们我有一个我无法察觉的错误。请帮助我。在此代码中,我想计算一个百分比,但在计算后,变量中存在零值存储"百分比"

int _tmain(int argc, _TCHAR* argv[])
{
    int total_marks, obtained_marks, percentage;
    total_marks = 1100;
    cout << "enters yours obtained marks"<<endl;
    cin >> obtained_marks;
    percentage = (obtained_marks / total_marks) * 100;
    cout << "yours percentage =" << percentage;
    if (percentage >= 60)
    {
        cout << "you have passed with first division";
    }
    cout << "yours pecentage is=" << percentage;
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

整数除法向零截断。

鉴于

int total_marks, obtained_marks, percentage;

percentage = (obtained_marks / total_marks) * 100;

如果obtained_marks小于total_marks,则(obtained_marks / total_marks)的值将为零。在那种情况下,

percentage = (obtained_marks / total_marks) * 100;

也将为零。

甚至

percentage = (obtained_marks / total_marks) * 100.0;

将为零,因为括号中的值仍为零。

一种更好的方法是:

percentage = ( 100 * obtained_marks ) / total_marks;

答案 1 :(得分:0)

获得的标记和总标记是整数,因此当你分割时你得到零。将数据类型更改为float或double。