显示零值的变量百分比
Variable percentage displaying zero value
嘿,我有一个无法检测到的错误。请帮助我。在此代码中,我想计算一个百分比,但是计算后,变量"百分比"中有一个零值存储
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;
获得的标记和总数是整数,因此分隔时您将获得零。将数据类型更改为浮动或双重。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 显示零值的变量百分比
- 查找向量C++中变量之间的百分比差异