简体   繁体   English

printf 中的变量有什么作用

[英]what does the variabel in printf do

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));"我希望它像这样打印 "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)));"代码在我这样打印之前不起作用“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 
}

pow returns a double. pow返回一个双精度值。 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).第三个参数需要%lf格式,否则在尝试使用 integer %d格式格式化浮点值时会出现未定义的行为(大多数编译器会发出有关此 BTW 的警告)。

Assigning the result to an integer workarounds the issue.将结果分配给 integer 可解决该问题。 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.您可以查看integer 功率算法 pow is more suited for floating point operations. pow更适合浮点运算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM