Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Questions:
Very easy but can't work in program, need help my brain is over used.
I am trying to calculate the value and get the percentage but I end up getting a 0.

int a = 122333; (value here could expand to hundred thousand)
int b = 128222; value here could expand to hundred thousand)

int answ = 0;

answ = (a - b);
answ = -5889;
answ = ((answ / a) * 100);

answ = 0 = definitely wrong
CORRECT ANSWER SHOULD BE: (-4.81)

Please enhance my basic code to get the right value because I always get 0

help :-<</xml>
Posted

answ = ((answ / a) * 100);

-5889 / 122333 in integer arithmetic is zero. If you want the real values then convert your numbers to doubles.
 
Share this answer
 
Comments
Dalek Dave 5-Sep-10 16:17pm    
good answer
Abhishek Sur 5-Sep-10 18:55pm    
Reason for my vote of 5
Good answer.
#realJSOP 6-Sep-10 6:09am    
If you want the most accurate response, you want to use decimal.
answ = ((answ / a) * 100);

The integer (-5889 / 122333) is 0, 0 * 100 is 0 so your program is correct.
The integer (100 * answ / a) would evaluate to -588900 / 122333 which is -4 nearer to your wish.

cheers,
AR
 
Share this answer
 
Comments
dabuskol 5-Sep-10 14:51pm    
I haven't tried your answer because I went out of the office to think load but monitoring my mails. How can I retain the negative value? Is it correct to use Math.Sign(answ) either the output is + or -.
thanks
Alain Rist 5-Sep-10 15:00pm    
Use float, double or decimal C# types to get an usable value :)
To make it simple.

Change

C#
int answ = 0;



Into

C#
double answ = 0;


then

MIDL
answ = ((answ / a) * 100);//= -4,81390957468549
 
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