-1

The Question:

I am using Visual C# Express 2010. I am trying to divide three integers, however, the result is always 0.

My Code:

//earlier in the code:
int totalKeywords = 3;

//the problem code:
decimal onePercent = 100 / totalKeywords / 100;  //100% divided by the number of keywords divided by 100 to make one percent

MessageBox.Show(onePercent);

//result: 0
//what I want: 0.33 or more acurate

What I've tried:

  • I've changed the value of totalKeywords
  • I've tried onePercent as a double, int, float, ect.

Guesses:

  • It could be that the built-in math doesn't work for some reason (WHY??)
  • It could be that decimal / int / float, etc. don't hold decimals (I don't think so)

My Efforts:

Community
  • 1
  • 1
Cullub
  • 2,901
  • 3
  • 30
  • 47

3 Answers3

4

try 100m / totalKeywords / 100

you have to define one of your numbers (at least) as decimal.

100 is an int

100m is a decimal

http://msdn.microsoft.com/en-us/library/364x0z75.aspx

If you want a numeric real literal to be treated as decimal, use the suffix m or M, for example:

decimal myMoney = 300.5m;
Bruno
  • 4,685
  • 7
  • 54
  • 105
4

Let's break it down:

decimal onePercent = 100 / totalKeywords / 100;

First, divide the integer literal 100 by the integer variable totalKeywords (value is 3). Result: integer 33.

Next, divide the result 33 by the integer literal 100. Result: integer 0.

The right-hand expression has type int, value 0. Convert that implicitly to the decmal 0m, so you can then assign that to the decimal variable onePercent.

Result: 0m.

To fix, as others have noticed, make the leftmost constant (if not all of them, for clarity) into a decimal. This will do, as the ints will implicitly convert to decimal:

decimal onePercent = 100m / totalKeywords / 100;

This is totally unambiguous, if a little over the top:

decimal onePercent = 100m / (decimal)totalKeywords / 100m;
phoog
  • 42,068
  • 6
  • 79
  • 117
2

on right side after calculation you will get only integer, then it will be assigned to decimal, so it gives you 0.

Nitin Aggarwal
  • 451
  • 1
  • 7
  • 18