Today I was trying to write a program that would sum up the integer input by user. For example if user input 683 it would return 6 + 8 + 3 = 17.
But I encounter some weird problem in my code
The Code :
#include
using namespace std;
int computeSum(int num);
int computeInteger(int num, int position);
int main()
{
int num;
int sum;
int total;
cin >> num;
total = computeSum(num);
cout << total;
return 0;
}
int computeSum(int num)
{
int position = 10;
int temp = num;
double total = 0;
bool finish = false;
while(!finish)
{
total = total + computeInteger(num, position);
if(num/ position == 0)
break;
position *= 10;
}
return total;
}
int computeInteger(int num, int position)
{
double subtract1 = (double) num / position; //if num = 683 and position = 10 , this will get 68.3
int subtract2 = num / position; //if num = 683 and position = 10 , this will get 68
double solution = subtract1 - subtract2; //take 68.3 - 68 = 0.3
return (int)(solution * 10); // return 0.3 * 10 = 3 , but instead of getting 3 this program return 0.3 * 10 = 2
}
The Question
- In the above code, when I input 683, for the function
computeInteger, instead of getting the last digit 3 I get 2 as a return value. This is very weird as I thought truncation would only remove the floating part and not doing any round up or down.When I test the codecout << (int)(0.3 * 10)I did get 3 , but not in the code above. It makes me confuse.
double subtract1 = (double) num / position; //if num = 683 and position = 10 , this will get 68.3
This is not entirely true, the 0.3 is not the rational number in base 2, those it will be very close to the 0.3 but less as the number is always rounded down, to narrow the mistake you can cast it to float or long float but this is not a case, as in your example it will always be 0.29, if you want to understand what really happens you must read about the number representation in the computers, it is very well described here:
http://en.wikipedia.org/wiki/Computer_number_format
The error you encountered is well known mistake also described in the wiki page:
http://en.wikipedia.org/wiki/Round-off_error
And Stack link:
What is a simple example of floating point/rounding error?