用c语言自行编写代码实现求n从1-100时,n的和,1/n的和,素数的个数。
时间: 2024-10-23 20:06:01 浏览: 48
在C语言中,我们可以分别编写函数来计算给定范围内的整数之和、倒数之和以及素数的数量。这里是一个简单的实现示例:
```c
#include <stdio.h>
#include <math.h>
// 计算数组元素之和
double sum(int arr[], int n) {
double total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
// 计算数组元素倒数之和,避免除以零的错误,这里假设n的范围不会包含0
double reciprocal_sum(double arr[], int n) {
double total = 0.0;
for (int i = 1; i <= n; i++) {
if (arr[i - 1] != 0)
total += 1 / arr[i - 1];
}
return total;
}
// 判断是否为素数
int is_prime(int num) {
if (num <= 1) return 0;
if (num == 2 || num == 3) return 1;
if (num % 2 == 0 || num % 3 == 0) return 0;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0)
return 0;
}
return 1;
}
int main() {
int n = 100;
int numbers[n]; // 存放1到n的整数
double reciprocals[n]; // 存放1到n的倒数
// 初始化数组
for (int i = 0; i < n; i++) {
numbers[i] = i + 1;
reciprocals[i] = 1.0 / (i + 1);
}
// 计算和与倒数和
double sum_of_numbers = sum(numbers, n);
double sum_of_reciprocals = reciprocal_sum(reciprocals, n);
// 计算素数数量
int prime_count = 0;
for (int i = 2; i <= n; i++) {
if (is_prime(i)) prime_count++;
}
printf("Sum of numbers from 1 to 100: %.2f\n", sum_of_numbers);
printf("Sum of reciprocals from 1 to 100 (excluding 0): %.2f\n", sum_of_reciprocals);
printf("Number of primes between 1 and 100: %d\n", prime_count);
return 0;
}
```
阅读全文