3
int a = 0, b, c, e, n = 25;
e = n;

while(n!=0)
{
  n=n/10;
  a++;
}

printf("%d",a);

b = e * e;
c = b % (pow(10, a));
if(c==e)
  printf("automorphic");

对于线路

c=b%(pow(10,a)); 

编译器显示错误:

invalid operands of types `int' and `double' to binary `operator%' 
4

6 回答 6

7

pow 返回一个双精度数,并且您不能在双精度数上使用 % 。

于 2013-09-01T11:53:41.900 回答
3

pow 返回一个 double,您不能将其用作 % 的运算符。

尝试:

c=b%((int)pow(10,a));

反而。

于 2013-09-01T11:55:21.577 回答
2

根据其他答案:pow在您的程序中引入双打,然后您将它们转换回整数。

最好避免这个问题,然后:

int a = 1;
while(n!=0)
{
   n=n/10;
   a *= 10;
}
a /= 10;

b=e*e;
c=b%a;

(编辑)我标记了一行“可疑”,因为会发生什么n=0..9?你可能需要

while (n >= 10)
   ..

(再次编辑,叹息)对不起——上面的编辑是错误的,你需要总位数。a循环后需要调整。

于 2013-09-01T12:00:30.550 回答
0

%运算符只能对整数进行操作。pow函数返回 a double,这就是您收到错误的原因。

于 2013-09-01T11:57:36.917 回答
0

在 C/C++ 中,模运算符 ( %) 仅限于整数。您可以使用fmod (...)浮点模数,但您仍然需要匹配类型才能使用它。因此,无论您选择使用哪种解决方案,您都必须转换您的变量或表达式之一;我个人会使用整数模数。

这与 Java 和 C# 等语言形成鲜明对比,后者允许您在模运算符的一侧有一个整数,而在另一侧有一个浮点数,没有问题。当从其他语言移植到 C 时,这可能是可移植性问题的根源。

于 2013-09-01T12:00:02.223 回答
0

代码可以更正为:

int a = 0, b, c, e, n = 25;
e = n;
while(n!=0)
{
  n=n/10;
  a++;
}
printf("%d",a);
b = e * e;
/*
 call to pow() function returns a double value and b is an integer type variable.
 For any operation (here, modular division) the operands must be of same type.
 So, the double value returned from call to pow() function must be explicitly 
 casted to int type as shown in the code below. Also, the first argument to pow()
 must to be double (or, float) type. Here, 10 is integer type, correct it as 10.0. 
 The result will be fine.
*/
c = b % (int)(pow(10.0, a));
if(c==e)
printf("automorphic");
于 2013-09-01T17:46:32.997 回答