开发者

C++ program not behaving as expected, double is converting up when it shouldn't be

I was making a program that rounds up numbers with various decimal places, so as an example 2001.3666 would end up as 2001.37, I managed to make this work by adding 0.005 then times开发者_如何转开发 100 and converted to a int and then divided again by 100.

Everything worked fine, no issues there, was having some fun making some loops too and stuff, but then everything became odd.

you see the first line of then program that repeats what the user typed in begun to display the rounded figure instead of the actual figure the user typed.

after a while I came to the conclusion that it wasn't my code, because I started a new project and quickly made up this code:

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


int main()
{
  cout << "enter: ";
  double numberWithDecimalPlaces;
  cin >> numberWithDecimalPlaces;
  cout << "you entered " << numberWithDecimalPlaces << endl;

  system("pause");
  return 0; 
}

I type in 2001.3666 and the program goes to a newline even though I didn't code that in and replies with 2001.37

its exact output is:

enter: 2001.3666
you entered 2001.37

now this is a brand new program in a new project without any of the same variable names as my earlier project and the user input figure is being rounded up, unless cin >> variable is automatically rounding up which i find unlikely it looks like some code from the earlier program is still in memory and conflicting with this code.

which is again unlikely right??

i'm using visual studio 2010 on win7


The default precision for cout in C++ is 6 digits, and so 2001.3666 will display as 2001.37, but 201.3666 should display as 201.367.

You can increase the precision like this:

#include <iomanip>
...
cout << "you entered " << setprecision(10) << numberWithDecimalPlaces << endl;


Numbers are often rounded when displayed, but you can control how much. Read http://www.cplusplus.com/reference/iostream/manipulators/setprecision/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜