tags:

views:

163

answers:

4

Hello,

I was very surprised when I found out my code wasn't working so I created a console application to see where the problem lies and I've got even more surprised when I saw the code below returns 0

    static void Main(string[] args)
    {
        float test = 140 / 1058;
        Console.WriteLine(test);
        Console.ReadLine();
    }

I'm trying to get the result in % and put it in a progress(meaning (140 / 1058) * 100) bar on my application,the second value(1058) is actually ulong type in my application,but that doesn't seem to be the problem.

The question is - where the problem is?

+5  A: 

You are using integer arithmetic and then converting the result to a float. Use floating-point arithmetic instead:

float test = 140f / 1058f;
erikkallen
@enrikkallen,I'm sorry,I forgot to mention I get the second value from a function,which returns ulong type(in my application) ,how do I add that "f" in the end of the ulong variable?
John
cast it from a ulong to a float by putting (float) in front of the function result before you divide.
Byron Ross
However, if it's ulong you probably want to convert it to double instead to prevent precision loss.
erikkallen
+3  A: 

The problem is that you are dividing integers and not floats. Only the result is a float. Change the code to be the following

float test = 140f / 1058f;

EDIT

John mentioned that there is a variable of type ulong. If that's the case then just use a cast opeartion

ulong value = GetTheValue();
float test = 140f / ((float)value);

Note, there is a possible loss of precision here since you're going from ulong to float.

JaredPar
I'm sorry,I forgot to mention I get the second value from a function,which returns ulong type(in my application) ,how do I add that "f" in the end of the ulong variable?
John
+1  A: 

This will work the way you expect ...

float test = (float)140 / (float)1058;

By the way, your code works fine for me (prints a 0.1323251 to the console).

JP Alioto
He edited his code.
Jason
The original question didn't have the float cast on the first number and hence it was doing integer division. The modified code works as you noted.
JaredPar
so now the question is irrelevant since there is no bug in it.
CiNN
+2  A: 

The division being performed is integer division. Replace

float test = 140 / 1058;

with

float test = 140f / 1058;

to force floating-point division.

In general, if you have

int x;
int y;

and want to perform floating-point division then you must cast either x or y to a float as in

float f = ((float) x) / y;
Jason