1

I am realy sorry to ask so simple question, but I realy can't figure out what is the problem. I want to convert any mark to 12 grade scale. I am trying to this as following:

double coef=(4/20)*12;
int mark=(int)coef;

But when i execute this code via debugger I see that coef is equal to zero. Why if this is double variable?

seeker
  • 3,255
  • 7
  • 36
  • 68

6 Answers6

12

Because even though you're assigning the result to a double value the calculation is performed using integers. And 4 / 20 in integer arithmetic in C# is 0. So you need something like

double coef = 4.0 / 20 * 12;

The 4.0 ensures that the rest of the calculation uses doubles. But often it's actually a good habit to make all your numbers explicit so that readers don't have to know about type conversion rules:

double coef = 4.0 / 20.0 * 12.0;
Joey
  • 344,408
  • 85
  • 689
  • 683
2

It's integer division until it needs to be converted...

4/20 = 0
0 * 12 = 0
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
2

Another alternative would be to do:

4 * 12 / 20;

But be aware that the result will truncate to 2 (because this is still integer division), which is okay, because that's what your cast to int would have done anyway.

Also, be aware that casting to int will truncate, not round. Use Math.Round if you want to actually round the result. It makes no difference with the numbers you gave, but I assume you'll not actually going to be only working with these constants!

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

You're doing integer division first, then multiplying by 12.

When you do:

(4/20)

That's evaluating to 0, because they're both integers.

Modify it so explicitly state doubles by:

double coef = (4.0 / 20.0) * 12;
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
1

try

double coef = (4.0/20.0)*12;

then

int mark = (int)coef;
Mihai
  • 2,740
  • 31
  • 45
1

All of the constants in the code are integers, and the result of 4/20, as an integer, is 0.

You'll want to rewrite it as:

(4.0/20.0)*12.0;
razeh
  • 2,725
  • 1
  • 20
  • 27