Search code examples
c++fmod

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

How to convert grams to kilograms? I've got the first part figured out, just not sure how to complete it? Would I just input grams to kg constant?


Solution

  • You're never assigning anything to kilograms before you print it. You should assign that from the formula.

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

    Also, this statement doesn't do anything:

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

    First of all, casting something to the same type has no effect. Second, you're not assigning the result of the cast to anything (casting doesn't modify its argument, it just returns the converted value). I suspect what you want is:

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

    But a simpler way to do this is with the floor() function:

    pounds = floor(pounds + .5);
    

    Casting a double to int will remove the fraction.