显示零值的变量百分比

Variable percentage displaying zero value

本文关键字:变量 百分比 显示      更新时间:2023-10-16

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

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;
}

整数划分向零截断。

给定

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;

获得的标记和总数是整数,因此分隔时您将获得零。将数据类型更改为浮动或双重。