输入一个正整数n,打印从2到n的所有素材(每5个一行)并求和
答案:2 悬赏:40 手机版
解决时间 2021-04-07 14:37
- 提问者网友:美人性情
- 2021-04-06 18:23
输入一个正整数n,打印从2到n的所有素材(每5个一行)并求和
最佳答案
- 五星知识达人网友:胯下狙击手
- 2021-04-06 18:45
是素数吧?
#include
#include
int is_prime(int tar){//判断是否为素数
int i = 2;
int end = sqrt((float)tar);
while(i <= end){
if(tar % i == 0)
return 0;
i++;
}
return 1;
}
int main(){
int n;
scanf("%d", &n);
int count = 0; //保存当前找到的素数个数
int sum_res = 0; //保存素数之和
int cur_idx = 2;
while(cur_idx < n){
if(is_prime(cur_idx)){
printf("%d ", cur_idx);
count++;
sum_res += cur_idx;
if(count % 5 == 0)
printf("\n");
}
cur_idx++;
}
printf("\n");
printf("%d\n", sum_res);
return 0;
}
#include
#include
int is_prime(int tar){//判断是否为素数
int i = 2;
int end = sqrt((float)tar);
while(i <= end){
if(tar % i == 0)
return 0;
i++;
}
return 1;
}
int main(){
int n;
scanf("%d", &n);
int count = 0; //保存当前找到的素数个数
int sum_res = 0; //保存素数之和
int cur_idx = 2;
while(cur_idx < n){
if(is_prime(cur_idx)){
printf("%d ", cur_idx);
count++;
sum_res += cur_idx;
if(count % 5 == 0)
printf("\n");
}
cur_idx++;
}
printf("\n");
printf("%d\n", sum_res);
return 0;
}
全部回答
- 1楼网友:执傲
- 2021-04-06 19:48
楼主你好!
你的错误挺多的!
1.首先你使用sqr(),这个函数的参数为double,所以你的k应该定义为double型;
2.if(m%2==0) m=m+1;当m等于1和2时,你这个还成立吗?显然还需要考虑m等于2和1的情况;
3.if(i>=k+1)明显不行不对是吧,for循环结束必然是i>k,所以应该为if(i>k)
4.system("pause");这个函数的头文件也没有!它是在#include下的
综上所述,修改后代码如下:
#include
#include
#include
main()
{
int m,t=0,i,n;
double k;
printf("输入正整数m和n(mk){
printf("%-4d",m);
t++;
if(t%5==0)printf("\n");
}
}
printf("\n");
system("pause");
}
希望我的回答对你有帮助!
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯