codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:
Search Forums:
  Hmm. Problem with a rounding and adding program. Help?  Sennet at 15:05 on Thursday, October 06, 2005
 

I'm working on a program that rounds and adds two real numbers provided by the user. All is going well, except that one of my sample runs is producing an undesired result, and I can't figure out how to fix it for the life of me. The code itself is rather simple, but one problem just. Won't. Work.

1.674 + 1.322 produces:

1.67
1.32
---------
3.00

It should be producing 2.99! D: Please, any advice on how to get it to produce the desired output would be very, very much appreciated.

Here's the code, for your referrence. Sorry about any formatting issues.

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

int main()
{
double a, b, sum;

cout << "Enter two real numbers to be rounded and added: ";
cin >> a >> b;
sum = a + b;

cout << endl << setw(30) << setiosflags(ios::fixed) << setprecision(2) << a << endl <<
setw(30) << b << endl << setw(30) << "---------" << setw(30) << endl << sum << endl;

return 0;
}



  Re: Hmm. Problem with a rounding and adding program. Help?  vector at 17:14 on Thursday, October 06, 2005
 

I tested ur code in Dev C++ and VC 6.0

with 1.674+1.322

It produced 2.996....i didn't find any rounding error

  Re: Hmm. Problem with a rounding and adding program. Help?  Sennet at 22:23 on Thursday, October 06, 2005
 

Did you, perhaps, set the precision as well? So it only shows two decimal places?

  Re: Hmm. Problem with a rounding and adding program. Help?  vector at 07:25 on Friday, October 07, 2005
 

Sorry i didn't set the precision

But here's another way to round of the result and get the desired result

float RoundTwoDecimals( float num )
{
float result = (int)(num * 100.0) / 100.0;
return result;
}

Example
--------
2.996
(int)(2.996 * 100.0) / 100.0
(int)299.6 / 100.0
299 / 100.0
2.99

Tell me if it solves ur purpose...otherwise i'll try to give u some other solution








CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums








Recent Forum Threads
•  Database Search
•  Access https in http page
•  IE page Redirect
•  Re: Javascript problem with document.write and accented characters
•  Re: sorting and Linked list
•  Re: need help linked list
•  Re: Help with arrays
•  Re: Reading from a file
•  Re: Why Use Method?


Recent Articles
Multiple submit buttons with form validation
Understanding Hibernate ORM for Java/J2EE
HTTP screen-scraping and caching
a javascript calculator
A simple way to JTable
Java Native Interface (JNI)
Parsing Dynamic Layouts
MagicGrid
Caching With ASP.Net
Creating CSS Buttons


© Copyright codetoad.com 2001-2006