Rounding Problem

why does cout<<(111.1*1.111)<<endl; print
123.432
when the output should be
123.4321
using visual studio 2010?
closed account (9wX36Up4)
i didn't use before visual studio 2010 but i think it should be because of the compilers default settings
Sorry for bad English
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

int main(){
	cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(4);

	cout<<(111.1*1.111)<<endl;

	while (true) {}

	return 0;}


The code:

1
2
3
cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(4);

Sets the number of digits after the decimal point to 4 when cout(ing) numbers of floating point type, I think.

I don't know how it works though, it's called a "magic formula" in the book I'm using (Absolute C++ by Walter Savitch).
Last edited on
Another book by Walter Savitch, Problem Solving with C++ 8e, also says it's a magic formula when early examples and exercises need it for proper output purposes but then explains it later on. I'm sure yours will too.
Last edited on
Is there any way to tell it to just trim off trailing zeros?
The default will truncate them, when no flags are set (e.g., cout.setf() sets flags). But as your topic post shows, if you have more than six digits you lose precision. As it might be better practice anyway, determine your significant figures and then set your flags and precision accordingly.
Topic archived. No new replies allowed.