我编写了以下代码:
1 #include<stdio.h>
2 #include<stdbool.h>
3
4 bool c[500];
5 void main()
6 {
7 int i,n=1,j;
8 for (i=2; i<500; i++)
9 {
10 if (!c[i])
11 {
12 printf("%d is the prime number %d\n", i,n);
13 n++;
14 j=2;
15 while (j*i<500)
16 {
17 c[j*i]=1;
18 j++;
19 }
20 }
21 }
22 }
显示500以下的质数;现在,我怎样才能让程序在短短几行内显示所有这些数字的总和(所有 500 以下的质数)?谢谢你的帮助,我是 C 新手
最佳答案
- 首先,将变量
sum
设置为零。 - 然后,每次当前输出质数时,也将其添加到
sum
中。 - 然后,完成后输出
sum
。
因此,假设您的代码可以正常工作,您需要更改上面的第 1 点:
int i,n=1,j;
进入:
int i,n=1,j,sum=0;
<小时/>
第 2 点涉及更改:
printf("%d is the prime number %d\n", i,n);
进入:
printf("%d is the prime number %d\n", i,n);
sum += i;
<小时/>
最后,第 3 点可以通过以下方式制定:
printf("Sum of all those primes is %d\n", sum);
在最后的右大括号之前。
<小时/>对代码的更改(包括注释和更合适的变量名称以提高可读性)将类似于:
#include <stdio.h>
#include <stdbool.h>
// Find/sum all primes less than this number.
#define LIMIT 500
// Flag indicating a number is non-prime, initialised to zeros.
bool isComposite[LIMIT];
void main (void) {
int num, mult;
int count = 1, sum = 0;
// Check every number for primeness.
for (num = 2; num < LIMIT; num++) {
// Ignore if composite.
if (!isComposite[num]) {
// Print prime, add to sum.
printf ("%d is the prime number %d\n", num, count++);
sum += num;
// Mark all multiples of it as composite.
for (mult = num * 2; mult < LIMIT; mult += num) {
isComposite[mult] = 1;
}
}
}
// Now just output the sum.
printf ("The sum of those primes is %d\n", sum);
}
如果是类作业,请勿抄袭,您可能会被发现。我添加它只是为了向您展示如果您遵循一些简单的规则(其中一些规则如下),代码的可读性会提高多少:
- 大量使用注释,通常是描述您在做什么,而不是如何做。
- 使用合适的变量名称。
- 尽量避免使用
500
等“神奇”常量。 - 在不影响可读性的情况下尽量减少垂直空间(通常最好在屏幕上看到尽可能多的代码)。
关于c - 500以下素数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27162419/