如何将磅转换为克和千克 - C++

How to convert pounds to grams and kilograms - C++

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main ()
{
//Declare variables
    double pounds, grams, kilograms;
//Declare constants
    const double LB2GRM = 453.592;
//Give title to program
    cout << "Pound to kilograms converter" << endl;
//Prompt the user to enter a weight
    cout << "Please enter a weight in pounds: " << endl;
    cin >> pounds;
//Displaying weight with two decimal points
    cout << setiosflags(ios::showpoint) << setprecision(2);
//Round off weight
    static_cast<double>(static_cast<double>(pounds +.5));
//Formula for conerversion
    double fmod(pounds * LB2GRM);
    cin >> grams;
//Show results
    cout << pounds << " pounds are equal to " << kilograms << " kgs and " << grams << " grams" << endl;

return 0;
}

如何将克换算成千克?我已经弄清楚了第一部分,只是不确定如何完成它?我会只输入克到公斤常数吗?

您永远不会在打印之前将任何内容分配给 kilograms。您应该从公式中分配它。

grams = pounds * LB2GRM;
// Divide grams by 1000 to get the kg part
kilograms = floor(grams / 1000));
// The remaining grams are the modulus of 1000
grams = fmod(grams, 1000.0);

另外,这条语句没有做任何事情:

static_cast<double>(static_cast<double>(pounds +.5));

首先,将某些东西强制转换为同一类型没有任何效果。其次,您没有将转换的结果分配给任何东西(转换不会修改其参数,它只是 returns 转换后的值)。我怀疑你想要的是:

pounds = static_cast<double>(static_cast<int>(pounds +.5));

但更简单的方法是使用 floor() 函数:

pounds = floor(pounds + .5);

double 转换为 int 将删除分数。