azam
azam

Reputation: 205

arithmetic operation not working

   float percentrelation = Individualrelatonshipdegree / relationshipdegree * 100;

This simple operation returns 0 while the value in Individualrelationshipdegree variable is 19 and in the relationshipdegree is 35. but it still returns 0. don't understand this problem. Any help will be appreciated.

Upvotes: 1

Views: 293

Answers (4)

pkuderov
pkuderov

Reputation: 3551

Just look at the calculation order. You want to div 19 by 35. So it's 0. And then multiply 0 and 100. It's also 0.
So you can try make first variable float for this expression by type casting:

float percentrelation = (float)Individualrelatonshipdegree / relationshipdegree * 100;

UPD Need to explain type casting moment. The calculation order is from left to right. And we have a rule that in operation with integer(int, byte, long long etc.) and float(float, double etc.) operands they both are type casted to float type. That's why we need just one type casting on first operand. And that's why another answer with 1.0f * your expression also works fine. Just two little different ways.

Upvotes: 4

huMpty duMpty
huMpty duMpty

Reputation: 14460

Have a look at float (C# Reference)

Bacially you are missing .F

eg. float x = 2.5F/3.5;

Upvotes: 0

L.B
L.B

Reputation: 116108

You are doing integer division. try

float percentrelation = 
    1.0f * Individualrelatonshipdegree / relationshipdegree * 100;

Upvotes: 4

Ravi Y
Ravi Y

Reputation: 4376

Are the two variables integers? If yes, you might want to cast them first.

float percentrelation = (float) Individualrelatonshipdegree / (float) relationshipdegree * 100;

Also, note that float is not very precise. Consider using decimal isntead.

Upvotes: 3

Related Questions