我想找出 100 以内的所有质数。这是我的代码。
// Find all the prime number within 100.
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main() {
int i,n;
int j = 0;
for ( n = 2; n <= 100; ++n) {
bool isPrime = true;
for (i = 2; i <= sqrt(float(n)); ++i) {
if(n % i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
++j;
printf("%d is a prime number\n",n);
}
}
printf("The total number of prime number within 100 is %d\n",j);
return 0;
编译时出现一处错误。
prime.c:14:8: error: expected expression before ‘float’
m = float(n);
^
谁能帮忙解决这个问题?谢谢。
最佳答案
你在转换时使用了错误的语法(你使用的是 C++ 的多种类型转换中的一种,但对于 C 来说只有一种方法)。变化:
sqrt(float(n))
到
sqrt((float)n)
但是请注意,sqrt
需要一个 double
,所以严格来说应该是:
sqrt((double)n)
另请注意,转换不是必需的,您可以只写:
sqrt(n)
关于c - 错误 : expected expression before ‘float’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161237/