Click here to Skip to main content
15,918,404 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi I'm going crazy with this easy situation

int abc = 0;
abc = 100 / 330 * 50;
Console.WriteLine(abc);


when I check abc is 0

But if I use this formula (
100 / 330 * 50;
) in Excel I return
15,15151515


What I have tried:

What's wrong ??

I need 15 like result...
Posted
Updated 1-Mar-22 1:17am

You are using integer arithmetic, and 100 / 330 is zero. You need to use either Double or Decimal types to get the correct answer:
C#
double abc = 0.0;
abc = 100.0 / 330.0 * 50;
Console.WriteLine(abc);
 
Share this answer
 
Comments
Maciej Los 1-Mar-22 12:29pm    
5ed!
Richard MacCutchan 1-Mar-22 12:35pm    
:thumbsup:
Integer division, my dear.
Try
C#
double abc = 0;
abc = 100.0 / 330 * 50;
Console.WriteLine(abc);
 
Share this answer
 
Comments
Maciej Los 1-Mar-22 12:29pm    
5ed!
Quote:
Hi I'm going crazy with this easy situation

In C, a division of integers result in an integer.
Thus 100/330 results in 0.
Try to replace
C++
abc = 100 / 330 * 50;

with
C++
abc = 100 * 50 / 330;
 
Share this answer
 
Comments
Maciej Los 1-Mar-22 12:29pm    
5ed!
Patrice T 1-Mar-22 12:47pm    
Thank you

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