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.