gpt4 book ai didi

c - 在单独的行上打印 10 范围内的素数

转载 作者:行者123 更新时间:2023-11-30 15:01:24 25 4
gpt4 key购买 nike

我想为每 10 个输入分离程序的输出(打印)。代码是求1到n中的素数以及它们的中位数。

我只想将 n 的每 10 个计数分开,例如:

primes from  1 to 10:
from 10 to 20:
from 20 to 30:

你能帮我做一下吗?

#include <stdio.h>

int main()
{
int n, x, y, p, sum, sumx;
float arm;
sum = 0, sumx = 0;
printf("\n Enter the maximum value of n =");
scanf("%d", &n);
printf("\n All prime numbers from 1 to %d are: ", n);

for (x = 2; x <= n; x++)
{
p = 1;
for (y = 2; y <= x / 2; y++)
{
if (x % y == 0)
{
p = 0;
break;
}
}
if (p == 1)
{
sum += x;
}
if (p == 1 && x != 1)
{
printf("%d ", x);
sumx++;
arm = (sum * 1.0) / sumx;
}
}

printf("\nThe sum of all Prime numbers from 1 to %d =%d", n, sum);
printf("\nTotal prime numbers is %d", sumx);
printf("\nThe median of all Prime numbers from 1 to %d is %.2f", n, arm);

return 0;
}

snapshot

最佳答案

只要 x 的值能被 10 整除,您就可以打印出“From _ to _:”:

#include <stdio.h>

int main()
{
int n, x, y, p, sum, sumx;
float arm;
sum = 0, sumx = 0;
printf("\n Enter the maximum value of n =");
scanf("%d", &n);
printf("\n All prime numbers from 1 to %d are: ", n);
int upper = n < 10? n : 10;
printf("\nFrom 1 to %d: ", upper);

for (x = 2; x <= n; x++)
{
p = 1;
for (y = 2; y <= x / 2; y++)
{
if (x % y == 0)
{
p = 0;
break;
}
}
if (p == 1)
{
sum += x;
}
if (p == 1 && x != 1)
{
printf("%d ", x);
sumx++;
arm = (sum * 1.0) / sumx;
}

if (x % 10 == 0 && x != n) {
int upper = (x + 10) > n? n : (x + 10);
printf("\nFrom %d to %d: ", x + 1, upper);
}
}

printf("\nThe sum of all Prime numbers from 1 to %d =%d", n, sum);
printf("\nTotal prime numbers is %d", sumx);
printf("\nThe median of all Prime numbers from 1 to %d is %.2f", n, arm);

return 0;
}

这将导致如下输出:

Enter the maximum value of n =29

All prime numbers from 1 to 29 are:

From 1 to 10: 2 3 5 7

From 11 to 20: 11 13 17 19

From 21 to 29: 23 29

The sum of all Prime numbers from 1 to 29 =129

Total prime numbers is 10

The median of all Prime numbers from 1 to 29 is 12.90

关于c - 在单独的行上打印 10 范围内的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com