Aniket Panke
Aniket Panke

Reputation: 1

Getting the 0 value after dividing the int values

I want to divide the two int values, but after dividing them I am getting only one value which is 0. Following is my formula:

int RH=(A1/M1)*100(where A1=145 and M1=199) where RH value should have 72 but I am getting 0, Can somebody please help me out?

Following is my code:

int RvalueH,RvalueV,RvalueT;
if((M1!=-1 || M1>0) && (M2!=-1 || M2>0) && (M3>0 || M3!=-1))
{
    int RH = (A1 / M1);
    int RV = A2 / M2;
    int RT = A3 / M3;
    RvalueH=RH*100;
    RvalueV=100*RV;
    RvalueT=100*RT;
}

Upvotes: 0

Views: 216

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98740

Honestly, this is a common mistakes for new programmers who try to perform integer division when they actually meant (or at least they think) to use floating point division.

From / Operator

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.

That's why when you calculate 145 / 199 result will be 0, not 0,728643216080402 etc.

Instead of that, multiple your 145 with 100 first and then divide the result wit 199. Since this still performs integer division, it disregards fractional part of the result and it will be 72 not 72,8643216080402 etc..

int A1 = 145, M1 = 199;
int RH = (A1 * 100) / M1; // RH will be 72

Upvotes: 3

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

Use double, round to zero and then convert to int.

eg var result = Convert.ToInt(Math.Round((double)R1/M1,0));

By the way M1>0 mean its always M1 != -1 true.

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this you need to convert the values to float to get the exact answer.

You should store the returned value of division in float variable to allow number with decimal points. As int will not hold the values after decimal point.

float RvalueH,RvalueV,RvalueT;
int A1 = 145;
int M1 = 199;
float RH =  (float)A1 /(float) M1;
RvalueH = RH*100;

Upvotes: 0

thumbmunkeys
thumbmunkeys

Reputation: 20764

You can rewrite your expression to get a non 0 result:

  int RH = 100 * A1 / M1;
  RvalueH = RH;

The same thing needs to be done for RvalueV and RvalueT.

The problem in your code is that RH = (A1 / M1) will yield 0 as it is a integer division. Multiplying by 100 first avoids the result becoming 0.

Upvotes: 0

Related Questions