Convert grams to ounces and pounds, if 1 ounce = 28,3495 gram and 1 Pound = 12 Ounce.
If anyone ask why 1 pound = 12 ounce not 1 pound = 16 ounce, yes its wrong but the question is like that.
1 2 3 4 5 6
#include<iostream>
usingnamespace std;
int main()
{
float ..........
#include<iostream>
usingnamespace std;
int main()
{
double wt_in_grams{0};
cout << "How many grams: ";
cin >> wt_in_grams;
// convert g to oz ...
// convert oz to lb ...
return 0;
}
BTW I know what europeans do with commas but are you sure 1 oz = 283.495 kg because that's what it says?
1 oz = 28.3495g, and 1 lb = 16 oz
OR,
1g = 1/28.3495 oz, and 1 oz = 1/16 lb
regardless of the numbers, just make constant doubles, eg
const double oztog=28.35;
and so on...
then its just a multiply.
...
cout << "5 oz is " << 5*oztog << " grams";
you can use the wrong info for the problem, whatever, it still becomes a constant for each conversion.
#include <iostream>
#include <iomanip> // <--- For "std::fixed", "std::showpoint" and "std::setprecision".
#include <limits>
int main()
{
constexprdouble GRAMS{ 28.34952 }; // <--- Can use whatever number you like.
constexprdouble POUNDS{ 16 }; // <--- Can be changed later.
double weightInGrams{};
std::cout << std::fixed << std::showpoint << std::setprecision(4); // <--- Used later when displaying floating point numbers.
std::cout << "\nEnter the weight in grams: ";
std::cin >> weightInGrams;
//while (std::cout << "\nEnter the weight in grams: " && !(std::cin >> weightInGrams))
//{
// std::cerr << "\n Invalid entry! Must be a number.\n";
// std::cin.clear();
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
//}
std::cout << "\n You entered: " << weightInGrams << '\n';
// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
Prefer to use "double"s over "float"s.
An example: " 28.34952" is likely to be stored as "28.34951999999999828". When displayed it will round up properly, but in a calculation it will be a bit short. And compared to a "float" "28.34951973". You can see there is a difference in the numbers and your calculations will come out differently.
For line 8. I know that you said you need to use 12, but get the program working correctly first. You may find a sue for it later. After the program is running you can later change the "16" to "12" before you turn it in.
The commented while loop is a better way of dealing with formatted input in case you enter something that is not a number. Either one will work.
Line 25 is for testing. You do not have to keep this.