-3

Very confused here, I have this code:

float temp = (1/10)*100;
Label.Text = Convert.ToString(temp);

for some reason my temp variable is being saved as 0 which means my label text is changed to 0 when I'm expecting 10, I have the same issue when using doubles instead. What has gone wrong?

Andrew Neate
  • 109
  • 1
  • 9

1 Answers1

0

Since 1, 10 and 100 are all integer values, the division is also an int value, rounded down. In this case 1/10 = 0 so (1/10)*100 = 0 If you do not want this try using floats:

(1.0f/10)*100

In case you're working with integer variables you have to convert them first. This can be achieved by casting, like so:

int a=1;
...
float b = ((float) a)/10; // b will be 0.1

Another quick way of doing this in a line with multiple operations is multiplying by 1.0f:

int x = 100;
float c = (a*1.0f)/x;  // c will be 0.01f