下列程序完成按每行5个的格式输出所有3位数中的质数,函数judge用来判断一个整数是否为质数。
下列程序中存在一些错误,请指出具体出错行的行号并说明出错原因(每行代码后我给出的注释内容为行号),并且在不改动程序的框架、变量定义的基础上给出正确的程序代码,或者说明将出错行做怎样的修改。
#include <stdio.h> //1
#include <math.h> //2
int judge(int n) //3
{ //4
int i, k; //5
k = (int)sqrt(n); //6
for (i = 1; i <= k; i++) //7
if (!n % i ) //8
return 0; //9
else return 1; //10
} //11
int main() //12
{ //13
int count ,i; //14
for (i=101;i<1000;i=i+2) //15
if (judge(i)) //16
{ //17
printf("%5d", i); //18
count++; //19
} //20
if (count % 5 == 0) //21
printf("\n"); //22
return 0; //23
} //24
第7行出错 应该是 i = 2; 是质数是从2开始判断是否能整除
第8行出错 n % i要加()先计算 if (!(n % i)) 否则!的优先级比%高 !n会先计算
第10行出错 应该去掉else, return 1应该放循环外
第14行出错 count要初始为0 count=0
第21和22行出错 if (count % 5 == 0) printf("\n"); 要放在上一个if中
你题目的解答代码如下:
#include <stdio.h> //1
#include <math.h> //2
int judge(int n) //3
{ //4
int i, k; //5
k = (int)sqrt(n); //6
for (i = 2; i <= k; i++) //7 应该是 i = 2;
if (!(n % i)) //8 n % i要加()先计算
return 0; //9
return 1; //10 去掉else, return 1应该放循环外
} //11
int main() //12
{ //13
int count=0, i; //14 count要初始为0 count=0
for (i = 101; i < 1000; i = i + 2) //15
if (judge(i)) //16
{ //17
printf("%5d", i); //18
count++; //19
if (count % 5 == 0) //21 放上一个if中
printf("\n"); //22
} //20
return 0; //23
} //24
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
一共3个错误:
(1)第8行,!的优先级比%高,if (!n % i)这么写逻辑错误,改成 if( !(n%i) )
(2)第19行,count++的时候没有初始化,需要再第14行中初始化count,第14行改成 int count=0,i;
(3)第21、22行会导致输出多个不必要的回车符,应该把他们放在第19行后面。
修改后的代码:
#include <stdio.h> //1
#include <math.h> //2
int judge(int n) //3
{ //4
int i, k; //5
k = (int)sqrt(n); //6
for (i = 1; i <= k; i++) //7
if (!(n % i)) //8 错误1: !的优先级比%高,这么写逻辑错误,改成 if( !(n%i) )
return 0; //9
else return 1; //10
} //11
int main() //12
{ //13
int count = 0, i; //14
for (i = 101; i < 1000; i = i + 2) //15
if (judge(i)) //16
{ //17
printf("%5d", i); //18
count++; //19 错误2:count没有初始化,会导致出错,把第14行改成 int count=0,i;
if (count % 5 == 0) //21 错误3:这个会导致输出多个回车符,把21、22行,移动到19行后面
printf("\n"); //22
} //20
return 0; //23
} //24
解答如下,改完后运行没问题的
#include <stdio.h> //1
#include <math.h> //2
int judge(int n) //3
{
//4
int i, k; //5
k = (int)sqrt(n); //6
for (i = 2; i <= k; i++) //7 **这里的1改为2
if (n % i == 0 ) //8 **这里改了 (!n % i)改成 n % i == 0
return 0; //9
return 1; //10 **else 去掉
} //11
int main() //12
{
//13
int count=0 ,i; //14 **count赋值
for (i=101; i<1000; i=i+2){ //15 **加了{
if (judge(i)) //16
{
//17
printf("%5d", i); //18
count++; //19
//20 **去掉}
if (count % 5 == 0) //21
printf("\n");}} //22 **加了}}
return 0; //23
} //24