2

Having trouble giving the correct digits for my $ output.

every time i plug in for example 8 in the statement i get numbers with 3 digits Ex. 10.9 While i would like it to display $10.90

I just added the setprecision hoping that it will fix the issue, did not work

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


int main()
{
    int Ts;    // holds Ts 
    float Price, Tcost, Total;


    cout << "How many shirts you like ?" << endl;
    cin >> Ts;

    Total = 12 * Ts;

    if ( 5 < Ts && Ts < 10)
        Tcost = (Total - (.10 * Total));
        Price = (Tcost / Ts);
        cout << "he cost per shirt is $" << setprecision(4) << Price << " and the total cost is $" << Tcost << setprecision(4) << endl;




    return 0;


}

2 Answers2

2

Use a combination of std::fixed(Which will set the amount of decimals after the point to be printed as decided by setprecision(N)) and std::setprecision(2) (So that two decimals are printed), and the code should now work:

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


int main()
{
    int Ts;    // holds Ts 
    float Price, Tcost, Total;


    cout << "How many shirts you like ?" << endl;
    cin >> Ts;

    Total = 12 * Ts;

    if ( 5 < Ts && Ts < 10)
        Tcost = (Total - (.10 * Total));
        Price = (Tcost / Ts); // The indentation is weird here
                              // but I will leave it as it is
        cout << "he cost per shirt is $" << fixed << setprecision(2) << Price << " and the total cost is $" << Tcost << setprecision(2) << endl;
    return 0;


}

The output I get from this is:

How many shirts you like ?
8
he cost per shirt is $10.80 and the total cost is $86.40
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

You have to write std::cout.setf(std::ios::showpoint); then it will work.

BAE HA RAM
  • 465
  • 1
  • 3
  • 10
  • Why would i have to put that in when previously i just kept it as 'cout' ?? – BlackHawkD721 Feb 15 '18 at 02:39
  • because std::cout don't show decimal point zero. So u must set the format of cout for show decimal point zero. – BAE HA RAM Feb 15 '18 at 02:49
  • The answer is correct, but not complete, unfortunately, @BlackHawkD721 . [The `setf` function](http://en.cppreference.com/w/cpp/io/ios_base/setf) sets a stream formatting option. [`std::ios::showpoint` is the option set](http://en.cppreference.com/w/cpp/io/ios_base/fmtflags), but you may find `cout << "The cost per shirt is $" << showpoint << setprecision(4) << Price << " and the total cost is $" << Tcost << endl;` a little more familiar. You will need to add `#include `. [Docs on `showpoint`](http://en.cppreference.com/w/cpp/io/manip/showpoint) – user4581301 Feb 15 '18 at 02:49