0

I want to get the answer of r^(a1/b1) but my code is not giving the correct output, can anyone help?

int main()
{
  float rat;
  float r=2.0;
  int a1=2;
  int b1=4;
  rat= pow(r,(a1/b1));
  printf("%f",rat);
    
return 0;
}

My output is coming as 1.000000 while it should come 1.414000. And my condition is that I have to take a1 and b1 as integer values.

Vishnu CS
  • 748
  • 1
  • 10
  • 24
  • 2
    `(a1/b1)` is zero. Remember, `a1` and `b1` are integers, so you're doing integer division. If you don't want that, cast one of them to `double` to force floating point division. – Tom Karzes Aug 07 '20 at 04:46
  • When dividing two integers with each other the result will be an integer, just case one of them to float and you should be fine. ((float)a1/b1) – AndersK Aug 07 '20 at 04:50
  • 1
    Unrelated suggestion: use `double` when dealing with floating-point values. – pmg Aug 07 '20 at 06:24

1 Answers1

0

The a1 and b1 are integers. When you are dividing this (a1/b1) you will get the output as zero. So internally the pow function will take it as 2^0which is 1 and this is the output you are getting here.

So the change you have to do is either you cast the a1 to float or b1 to float. Then this will work.

I will post a working code here.

#include <stdio.h>

int main ()
{
  float rat;
  float r = 2.0;
  int a1 = 2;
  int b1 = 4;
  rat = pow (r, ((float)a1 / b1)); //Casting the a1 to float
  printf ("%f", rat);
  return 0;
}

Output 1.414214 will be printed out. Here as you can see I cast the a1 to float. The same casting you can apply it for b1 also. This will also work.

For more info you can go Why dividing two integers doesn't get a float?

Hope it solved your problem.

Vishnu CS
  • 748
  • 1
  • 10
  • 24
  • 1
    Little reason to use `float` here, risk truncation and then use `double` math with `2.0`, `pow()` and `printf ("%f", rat);`. Suggest dropping `float` and using `double`. – chux - Reinstate Monica Aug 07 '20 at 12:34