关于C语言程序

来源:百度知道 编辑:UC知道 时间:2024/05/08 11:47:42
#include "math.h"
main()
{int m,i,k,h=0,leap=1;
printf("\n");
for(m=101;m<=200;m++)
{k=sqrt(m+1);
for(i=2;i<=k;i++)
if(m%i==0) {leap=0;break;}
if(leap){printf("%-4d",m);h++;
if(h%10==0) printf("\n");}
}
printf("\nthe total is %d",h);
}
此程序哪里出错了?

#include "math.h"
#include <stdio.h>

main()
{
int m, i, k, h=0, leap=1;
printf("\n");

for(m=101;m<=200;m++) {
k=sqrt(m+1);
for(i=2;i<=k;i++)
if(m%i==0) {leap=0;break;}
if(leap){
printf("%-4d",m);h++;
if(h%10==0) printf("\n");
}
leap = 1;
}
printf("\nthe total is %d",h);
}

首先忘了包含头文件
#incclude <stdio.h>

其次,你的leap在发现了一个数不是素数之后,被置零,但是在重新开始另一次循环之前,你的leap应该复位为1, 不然你后面就一直是0,你的内循环就一直退出,然后什么事都不做。

printf("\nthe total is %d",h);
} 是这里么 最后改为@h

这个程序本身没有错误,如果有的话只是语义上的错误。不过有些的方要注意。
1. 使用标准头文件,最好用
#include <math.h>
2. main函数返回int型应该写明,即:
int main()
{
/* 其他语句 */
return 0;
}
3. 使用sqrt函数时应该明确类型转换,特别在新的编译器上这个函数是一个重载函数,即:
k = (int)sqrt((double)