指数在C中不能正常工作
当我运行以下代码时指数在C中不能正常工作,c,exponent,C,Exponent,当我运行以下代码时 /*Program to find the greatest common divisor of two nonnegative integer values*/ #include <stdio.h> int main(void){ printf(" n | n^2\n"); printf("-----------------\n"); for(int n = 1; n<11; n++){ int n
/*Program to find the greatest common divisor of two nonnegative integer
values*/
#include <stdio.h>
int main(void){
printf(" n | n^2\n");
printf("-----------------\n");
for(int n = 1; n<11; n++){
int nSquared = n^2;
printf("%i %i\n",n,nSquared);
}
}
为什么“n^2”端生成错误的数字?有没有办法用C写上标和下标,这样我就不必显示“n^2”,而是可以将列的那一面显示为“n²”?使用
math.h
中的pow
函数
^
是按位异或运算符,与幂函数无关。是异或运算。您可以使用math.h函数“pow”,也可以编写自己的函数。^
是按位异或运算符。您应该使用math.h
标题中声明的pow
函数
#include <stdio.h>
#include <math.h>
int main(void) {
printf(" n | n^2\n");
printf("-----------------\n");
for(int n = 1; n < 11; n++){
int nSquared = pow(n, 2); // calculate n raised to 2
printf("%i %i\n", n, nSquared);
}
return 0;
}
#包括
#包括
内部主(空){
printf(“n | n^2\n”);
printf(“--------------\n”);
对于(int n=1;n<11;n++){
int nSquared=pow(n,2);//计算n提升到2
printf(“%i%i\n”,n,n平方);
}
返回0;
}
通过标记
-lm
包含数学库以进行gcc编译。正如其他人所指出的,问题在于^
是按位异或运算符。C没有求幂运算符
建议您使用pow()
函数来计算int
值的平方
这可能会奏效(如果你小心的话),但这不是最好的方法。pow
函数接受两个double
参数并返回一个double
结果。(有powf
和powl
函数分别对float
和long double
进行运算。)这意味着pow
必须能够处理任意浮点指数;例如,pow(2.0,1.0/3.0)
将为您提供二的立方根的近似值
与许多浮点运算一样,pow
也可能出现舍入错误。有可能pow(3.0,2.0)
产生的结果略小于9.0
;将其转换为int
将为您提供8
而不是9
。即使您设法避免了这个问题,从整数到浮点的转换,执行一个昂贵的操作,然后再转换回整数也是一个巨大的过度消耗。(该实现可能会使用整数指数优化对pow
的调用,但我不会指望这一点。)
有人说(有点夸张)过早优化是万恶之源,花在额外计算上的时间不太可能是显而易见的。但在这种情况下,有一种方法可以做你想做的事情,既简单又高效。而不是
int nSquared=n^2
哪个是不正确的,或者
int nSquared = pow(n, 2);
这是低效且可能不可靠的,只需写:
int nSquared = n * n;
pow
对于平方一个数字来说是一种过分的技巧,并且它会受到浮点舍入错误的影响。只需写入intnsquared=n*n代码>@OMGtechy我认为这不对n@Whymarrh我被其他东西搞混了,谢谢你指出。你关于写上标和下标的问题与你关于指数的问题无关。我建议你作为一个单独的问题提交。(这不是一件简单的事情,很可能取决于您的区域设置。)哈哈。。我第一次看到有人期望C.bolov中的^
是指数运算,似乎你对这个网站是新手。这可能是我白天看到的第三个。似乎很多人都有这个任务。
int nSquared = n * n;