This example program was created with the sole purpose of showing what setprecision and setw does. I dont understand the purpose of the third line that says "setprecision(5)". I commented the line out to see the difference but it looks the exact same. Is there no purpose?
cout << "\nSales Figures\n";
cout << "-------------\n";
cout << setprecision(5);
cout << "Day 1: " << setw(8) << day1 << endl;
cout << "Day 2: " << setw(8) << day2 << endl;
cout << "Day 3: " << setw(8) << day3 << endl;
cout << "Total: " << setw(8) << total << endl;
The setprecision() function is part of the "iomanip" library and is used when you need to output a float to a certain number of decimal places. This is good for displaying money amounts and other things that typically are shown with a set number of digits after the decimal point (even if those digits are 0).
Say you have a float called price: If you stored 10.0 in that float, C++ would not know how many decimal points to output when you print into the screen; setprecision(2) would make the output 10.00.
You can find the documentation at this link: https://cplusplus.com/reference/iomanip/setprecision/.
It includes the following code as an example of how setprecision() works.
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.1415
std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.14159
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n'; // This outputs 3.14159
std::cout << std::setprecision(9) << f << '\n'; // This outputs 3.141590000
return 0;
}
Note that setprecision() is only applicable to data types with decimal points such as floats and doubles.
My program executes just fine, but I was wondering how to align my output so cents line up rather than dollars.
We've only started class a couple weeks ago, so we haven't gone over this yet. My professor says it's okay for now if they don't align, I guess I'm just OCD about it. Plus, I think it looks a lot cleaner.
Also, if the bill is $38.40, would that be four significant figures? Sorry, I haven't taken math in a while. In my output, I'm getting up to five significant figures for some reason. The most I have is four. How would I fix this, using setprecision?
cout << "Bill \t \t $ " << bill << endl;
cout << "Tax at 10.5% \t \t $"<<tax<< endl;
cout << "Sub-total \t \t $"<<subTotal<< endl;
cout << "Tip at 20% \t \t $"<<tip<< endl;
cout << endl;
cout << "Total Bill \t \t \t $"<<totalBill<< endl;
As you see, I've been trying it using the tab escape. As a reply suggests, I should use setw?
Edit for 9/10:
I've gotten all my dollar amounts rounded to two decimals, except for the bill, and I don't know how to fix it. Thanks for all the info you've given me, but it's too advanced for what we're doing right now, so I've just aligned things manually. I still need to add setw and then fix everything once that's there. I'm just asking about why the bill is only three digits. It's probably something super simple that's going right over my head.
// Declare variables
double bill, tax, subTotal, tip, totalBill;
// Variables
bill = 38.40;
tax = .105;
tip = .20;
// Calculate the tax
tax = bill * .105;
// Calculate sub-total of bill
subTotal = bill + tax;
// Calculate tip
tip = subTotal * .20;
// Calculate total amount of bill
totalBill = subTotal + tip;
cout << "Bill" " $ " << setprecision(4) << bill << endl;
cout << "Tax at 10.5%" " $ " << setprecision(3) << tax << endl;
cout << "Sub-total" " $ " << setprecision(4) << subTotal << endl;
cout << "Tip at 20%" " $ " << setprecision(3) << tip << endl;
cout << endl;
cout << "Total Bill" " $ " << setprecision(4) << totalBill << endl;
Edit: I "fixed" it. All is good now.
If you're printing money, I recommend you look at C++'s money I/O.
std::put_money will ensure you are international compliant and printing with correct rounding/precision.
Set the locale of std::cout for USD.
std::showbase will decide whether to print the $.
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
Use std::setw and std::left for formatting.
Here is an example of printing your data:
#include <iostream>
#include <string>
#include <iomanip>
//row data from example
struct Row{
std::string description;
float amount;
};
//function for printing a row
void Print(Row row);
int main(){
//example rows
Row a{"Bill",3840};
Row b{"Tax at 10.5%",403};
Row c{"Sub-total",4243};
Row d{"Tip at 20%",848};
Row e{"Total Bill",5091};
//settings for printing as USD
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << std::showbase;
//format printing
Print(a);
Print(b);
Print(c);
Print(d);
std::cout << '\n';
Print(e);
}
void Print(Row row){
static const int COLUMN_WIDTH{14};
std::cout << std::setw(COLUMN_WIDTH) << std::left << row.description;
std::cout << " " << std::right << std::put_money(row.amount) << '\n';
}
result:
Bill $38.40
Tax at 10.5% $4.03
Sub-total $42.43
Tip at 20% $8.48
Total Bill $50.91
One possible way is to use setw.
cout<<setw(5)<<4.55<<endl;
cout<<setw(5)<<44.55<<endl;
output:
4.55
44.55
Update:
as Jonathan Leffler pointed out, the << operator resets the width, hence the code is updated to show it should be repeated.
I would do something like:
std::cout << std::setw(15) << std::left << "Bill";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << bill << std::endl;
std::cout << std::setw(15) << std::left << "Tax # 10.5%";
std::cout << std::setw(15) << std::right << std::fixed << std::setprecision(2) << tax << std::endl;
This sets the width of the output for each "column" to 15 characters so you don't have to rely on tabs. All of the the "labels" will be left justified, and all of the prices will be right justified and printed to 2 decimal places. This is a bit more robust than relying on tabs, where you don't have control as to how many characters are used. You can't do proper justification with tabs.
Okay so I have a calorie calculator that is supposed to be separated into the five functions including main seen below. My issue is that I get a compiler error because the variables from the inputNumber function and calculateCalories function cannot be read by any of the other functions once they are obtained. I am not allowed to use Global variables. There must be something I am missing to be able to read the variables within the main function then output them into the other functions to get the proper output. Any help would be appreciated.
Here is the code as it stands:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int Lbs, hourr, hourW, hourWe, hourb;
double calBad, calRun, calWal, calWei;
string name;
cout << "Welcome to Megan McCracken's Workout Calculator!" << endl;
cout << endl;
cout << "Please enter your name: ";
getline(cin, name);
inputNumber(Lbs, hourr, hourW, hourWe, hourb);
calculateCalories(Lbs,hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
displayHeadings(name);
displayLine(hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
system("pause");
return 0;
}
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
{
cout << "Please enter your weight: ";
cin >> Lbs;
return Lbs;
cout << "Please enter the minutes spent playing badminton: ";
cin >> hourb;
return hourb;
cout << "Please enter the minutes spent running: ";
cin >> hourr;
return hourr;
cout << "Please enter the minutes spent walking: ";
cin >> hourW;
return hourW;
cout << "Please enter the minutes spent lifting weights: ";
cin >> hourWe;
return hourWe;
cout << endl;
}
double calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
const double Badburn = .044, Runburn = .087, Walkb = .036, Weightb = .042;
double calBad, calRun, calWal, calWei;
calBad = (Badburn * Lbs) * hourb;
calRun = (Runburn * Lbs) * hourr;
calWal = (Walkb * Lbs) * hourW;
calWei = (Weightb * Lbs) * hourWe;
return calBad;
return calRun;
return calWal;
return calWei;
}
void displayHeadings(string name)
{
cout << "Here are the results for " << name << ": " << endl;
cout << endl;
cout << "Activity" << right << setw(18) << "Time" << right << setw(10) << "Calories" << endl;
cout << "--------------------------------------" << endl;
}
void displayLine(int hourb,int hourr, int hourW, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
int HB, MB, HR, MR, HW, MW, HWE, MWE, Hour, Min;
double Calorie;
HB = (hourb / 60);
MB = (hourb % 60);
HR = (hourr / 60);
MR = (hourr % 60);
HW = (hourW / 60);
MW = (hourW % 60);
HWE = (hourWe / 60);
MWE = (hourWe % 60);
Calorie = calBad + calRun + calWal + calWei;
Hour = (hourb + hourr + hourW + hourWe) / 60;
Min = (hourb + hourr + hourW + hourWe) % 60;
cout << "Badminton" << right << setw(14) << HB << ":" << setfill('0') << setw(2) << MB << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calBad << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Running" << right << setw(16) << HR << ":" << setfill('0') << setw(2) << MR << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calRun << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Walking" << right << setw(16) << HW << ":" << setfill('0') << setw(2) << MW << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWal << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Weights" << right << setw(16) << HWE << ":" << setfill('0') << setw(2) << MWE << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWei << endl;
cout << "--------------------------------------" << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Totals" << right << setw(17) << Hour << ":" << setfill('0') << setw(2) << Min << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << Calorie << endl;
cout << endl;
}
If you want to modify passed-in variables within a function in C++, you should be passing them in by reference (default is by value, meaning you get a copy of the variable which is effectively thrown away when the function exits).
So, by way of example:
void xyzzy (int plugh) { plugh = 42; }
int main() {
int twisty = 7;
xyzzy (twisty);
cout << twisty << '\n';
return 0;
}
will output 7 because twisty was passed by value and changes to it within the function will not be echoed back to the caller.
However, if you pass by reference with:
void xyzzy (int &plugh) { plugh = 42; }
// ^
// This does the trick.
then you'll find it outputs 42 as desired.
For your particular case, you want to look at the variables in the argument list of inputNumber:
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
Any of these that you want echoed back to the caller (and that looks like all of them from a cursory glance) should be pass by reference rather than pass by value.
You should also look into calculateCalories as well, since that is doing the same thing. Keep in mind that only the ones you want to change and echo back to the caller need to be pass-by-reference. So that's only the ones starting with cal.
And, since you're using the pass-by-reference to modify the variables, there's absolutely no reason to return anything from that function so it can be specified as void calculateCalories ... and the return statements removed (in any case, only the first return would have actually done anything, the others would have been unreachable code).
If you haven't yet got to the point where you can use references in your classwork (as seems to be indicated by one of your comments), you can do what C coders have been doing for decades, emulating pass-by-reference with pointers. In terms of the simplified example above, that would mean modifying the function to receive a pointer to the item you want changed, changing what it points to, and calling it with the address of the variable to be changed:
void xyzzy (int *pPlugh) { *pPlugh = 42; }
int main() {
int twisty = 7;
xyzzy (&twisty);
cout << twisty << '\n';
return 0;
}
However, it's a poor substitute for the real thing and, if your educator is trying to teach you that, it's the same as if they're getting you to use printf/scanf rather than cout/cin for user I/O: it's certainly possible in C++ since the language includes legacy C stuff, but it's not really teaching you the C++ way.
People who claim to be C++ developers but really code in C using a C++ compiler, are a rather strange breed that I like to call C+ developers - they've never really embraced the language properly. The sooner people put aside the legacy stuff, the better they'll be as C++ developers.
Pass the variables by references. Then the functions will be able to edit them.
Your other solution (not so much of a good idea but still working) is to create a struct/class and make the functions return it.
P.S. Your code won't work if the functions are in this order unless you add their signatures in the beginning:
int main();
int inputNumber(int,int,int,int,int);
//and so on
In input number, you can not use 'return' to return each value - it will do the first return statement.
In C++ you can use pass by reference so that values assigned to the variables will be passed back up.
In this case, via the input variables would be inputNumber so use '&' to denote the vaiables are references:
void inputNumber(int &Lbs, int &hourr, int &hourb, int &hourW, int &hourWe)
{
.
.
.
}
Similar idea for calculateCalories, get rid of the returns:
void calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double &calBad, double &calRun, double &calWal, double &calWei)
{
.
.
}
Note that we are only bothering to pass to reference for the variables that we will be passing back.
I'm working on a project where I need to do some math and give the user output with dollars in it, so I would like to have my console tell the user an answer like $20.15 instead of $20.153. I used the set precision function as such:
cout << setprecision(2);, but rather than have the numbers become what I want them to be, they are converted into scientific notation.
I'm outputting a lot of numbers, so having a function like setprecision would be best for me for ease of use.
How do I properly have the numbers displayed with only two decimal places and not have the console give me numbers in scientific notation?
Thanks
Nathan
EDIT:
Here is the part of my code I'm having problems with:
int main() {
cout << setprecision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
Obviously there's more to it, but this is what I need help with.
To fix that, you should use fixed floating-point notation for cout. You can find more info here.
Try addind cout << fixed to your code, like the code below. To set the precision to 2, you can use the precision property.
cout << fixed;
cout.precision(2);
Here is the complete code:
using namespace std;
int main() {
cout << fixed;
cout.precision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
}
Iostreams are a pain for formatting floating-point values. But why are you using floating-point to represent currency values? You should store integer pennies (or tenth-pennies) because, though you're not measuring in whole numbers of dollars, your values are actually fixed-point. And you really don't need the trouble that floating-point brings. And then you can stream the whole and "fractional" parts of your value separately (use / and %!), as integers, with a '.' in the middle.
In the meantime, try std::fixed.
Cheat and watch purists go crazy...
double time; //Only want two decimal places.
double timeCon = time * 100.0; //Pull out the two decimals I want.
int timeCut = timeCon; //Cut all decimal values.
double timeRevert = timeCut / 100.0; //Laugh.
cout << timeRevert << endl; //Watch heads explode.
I am currently working on a project for my C++ class and have come across an issue that I just cant seem to figure out on my own.
I am creating a weight conversion program that asks the user to input their weight (in kilograms), and outputs their weight in pounds as well as the weight they entered in kilograms (both rounded to 2 decimal places).
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declarations
double kg = 0.0;
double lbs = 0.0;
double conversionRate = 2.2;
//INPUT
cout << "Enter Your Weight (kilograms): ";
cin >> kg;
//PROCESS
lbs = (kg * conversionRate);
//OUTPUT
cout << "Weight Entered: " << setprecision(2) << kg << " Kg" << endl;
cout << "Converts to: " << setprecision(2) << lbs << " lbs" << endl;
cout << "\n\n";
system("pause");
return 0;
}
This is the output I am getting for pounds:
These are the variable values when debugging:
I cant seem to figure out why it is outputting the data that is shown in the screenshot, and why its not showing decimal places as well on the kg?
Any help is appreciated!
You need to use fixed.
Either do a
cout.precision(2);
cout << "Weight Entered: " << fixed << kg << " Kg" << endl;
cout << "Converts to: " << fixed << lbs << " lbs" << endl;
or more like you did
cout << "Converts to: " << fixed << setprecision(2) << lbs << " lbs" << endl;
This outputs to:
Weight Entered: 63.5028
There is a linked case here linked to this case
Cheers
Stian
You want to do
cout << fixed << showpoint << setprecision(2) << lbs << " lbs" << endl;