-1
Why didn't this code work after adding "res=pow(arr[i],x)"

I want it to print like this "printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));" The code doesn't work untill i print like this "printf("%d * %d = %d \n",i+1,x,res)));"

#include<stdio.h>
#include<math.h>
int main()
{
int arr[5];            
for(int i=0 ; i<5 ; i++){
printf("enter the numbers %d\n",i+1);
scanf("%d",&arr[i]);
}
int x;
printf("what is power would you like...\n");
scanf(" %d",&x);
printf("The power of the array elements is...\n");
for(int i=0 ; i<5 ; i++){
printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));
}
return 0;   //  1*2=1*1    ,    3*2=3*3 
}

1 Answers1

0

pow returns a double. You need %lf format for the third argument or you'll get undefined behaviour trying to format a floating point value with an integer %d format (most compilers issue a warning about this BTW).

quickfix

printf("%d * %d = %lf \n",i+1,x,pow(arr[i],x));

Assigning the result to an integer workarounds the issue. That's why it works then (but sometimes it leads to rounding errors so beware!)

You may have a look at integer power algorithms instead. pow is more suited for floating point operations.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219