Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

I am using vs2010 with c# language.I am go to divide a two number i can't get the Expected output.I am using Following Coding.

Int32 tmpcnt = 0;
Double totalHours ;

tmpcnt=105094;

totalHours = tmpcnt / 60000;

I expect the answer is 1.75 but i get the answer is 1.0 only any tell me what is my mistake or give the solution.


thaks advance!....
Posted

You are using an integer division (in the line totalHours = tmpcnt / 60000;, both tmpcnt variable and 60000 constant are integers.
Thus, you get the integer division result.

If you want a real division, you should use double type for at least one of the operands.
For example:
C#
totalHours = tmpcnt / 60000d;
// OR
totalHours = tmpcnt / 60000.0;


This will give you expected result.
 
Share this answer
 
v2
Comments
Krunal Rohit 29-Sep-15 7:48am    
Yeah. 5!

-KR
phil.o 29-Sep-15 7:51am    
Thanks :)
You can cast an int to a double and a double to an int. Int to double is loss-less but double to int will lose precision. it will round down.

tmpcmt / 60000 is int / int so the result will be int. The result will be rounded down.

To change this, just make one number or the other not an int. The equation will try to keep the most precision.

tmpcmt / 60000.0 is now int / double which will keep the double precision.

In other cases you may need to cast:

int myint = 60000
tmpcmt / (double)myint

Hope that helps ^_^
Andy
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900