c++ - 从公斤换算成英石和磅时

标签 c++

好的,所以当我输入我的体重(以公斤为单位)时,我得到了正确的石头输出,但我的体重不对。

假设 2.2 磅是一公斤 14lbs 是一 block 石头

它应该给你以石头为单位的重量和以磅为单位的小数点,我的石头很好,但磅数与脚本有任何帮助

#include <iostream>
using namespace std;
//declarations
const float LBS_PER_KG=2.2;
const float LBS_PER_STONE=14;
const float STONE_PER_KG=6.36;

int main()
{

float weightInKG;
float weightInSTONE;
float weightInLBS;

cout <<"enter a measurement in Kilograms";
cin >> weightInKG;

weightInSTONE = static_cast<int>(weightInSTONE*LBS_PER_KG/LBS_PER_STONE);
weightInSTONE = weightInKG/STONE_PER_KG;
weightInLBS = weightInKG / LBS_PER_KG;
cout <<weightInKG<<"KG = "<<weightInSTONE<<"Stones and"
  <<weightInLBS<<"Pounds";
cout <<endl;
 return 0;
}

最佳答案

您对 weightInLBS 的计算是错误的。你必须乘法而不是除法

weightInLBS = weightInKG * LBS_PER_KG; // [lbs] = [kg] * ([lbs] / [kg])

也许为了避免进一步更改程序时出现一些问题,您应该将变量初始化为零

float weightInKG = 0;
float weightInSTONE = 0;
float weightInLBS = 0;

对于您在评论中提出的问题,如果您只想显示以磅为单位的石 header value 的小数点分隔符后的值,您应该使用此计算

weightInLBS = (weightInSTONE - static_cast<int>(weightInSTONE)) * LBS_PER_STONE;
// cut off the value before decimal separator and convert it to LBS

这是显示结果

cout <<weightInKG<<"KG = "<<static_cast<int>(weightInSTONE)<<"Stones and"<<weightInLBS<<"Pounds"<<endl;

关于c++ - 从公斤换算成英石和磅时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46485919/

相关文章:

c++ - 在 C++ 上具有公共(public)访问器的私有(private)字段

c++ - 当用文字替换变量用法时,程序会变慢很多,为什么?

c++ - <<运算符(operator)只打印一个空行

c++ - 如何在 header 中使用尚未定义的数据类型?

c++ - 如何将 __m128 转换为整数

c++ - 无法在 Visual Studio 2013 中正确创建 C++ 项目

c++ - 用于查找相似的连续类型名称的模板元程序

c++ - 从包含十六进制数的 std::string 或 QString 创建 std::bitset 或 QBitArray

C++ 从父引用调用子方法

c++ - 如何查找地址是否属于代码或数据部分