[英]wrong value while calculating power in a loop
I have problem in calculating a power of an integer in a C language. 我在使用C语言计算整数的幂时遇到问题。
I have to convert an array value to an equivalent integer ie {5,3,0,5,3} to 53053 我必须将数组值转换为等效整数,即{5,3,0,5,3}到53053
I have the following code 我有以下代码
int repsEqual(int a[], int len, int n)
{
int temp = 0;
int i = 0;
for(i; i < len;i++)
{
temp = temp + a[i] * pow(10, (len - (i+1)));
}
if(temp == n) {
return 1;
}
else {
return 0;
}
}
It always return 0. Since the power is wrongly outputted. 它总是返回0。由于电源输出错误。 {5,3,0,5,3} returns 53052. {5,3,0,5,3}返回53052。
Please help me guys 请帮我
You are mixing floating point and integer arithmetic and suffering from rounding problems as a result. 您正在混用浮点数和整数算术,结果遭受了舍入问题。 There is no need to call pow
, which is a floating point library function, and overkill for this assignment. 不需要调用pow
(这是一个浮点库函数),并且不必为此分配过多的费用。 A simpler implementation using just integer arithmetic would be: 仅使用整数算法的简单实现是:
int repsEqual(int a[], int len, int n)
{
int temp = 0;
for (int i = 0; i < len; i++)
{
temp = temp * 10 + a[i];
}
return (temp == n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.