刷完抖音随便写了道简单的题,写完发现运行错误,题的要求如下
Write a function double sum_sequence(int n)
that calculates and returns the sum \begin{equation*} \frac{1}{1} + \frac{1+2}{1 \times 2} + \frac{1 + 2 + 3}{1 \times 2 \times 3} + \frac{1 + 2 + 3 + 4}{1 \times 2 \times 3 \times 4} + \cdots + \frac{1 + 2 + \cdots + n}{n!} \end{equation*} where n
is a positive integer argument passed to the function. For example, sum_sequence(3)
should return the value (1/1) + (3/2) + (6/6) = 3.5.
大致意思就是
编写一个函数,计算并返回总和 \begin{equation*} \frac{1}{1} + \frac{1+2}{1 \times 2} + \frac{1 + 2 + 3}{1 \ times 2 \times 3} + \frac{1 + 2 + 3 + 4}{1 \times 2 \times 3 \times 4} + \cdots + \frac{1 + 2 + \cdots + n}{n!} \end{equation*} 其中是传递给函数的正整数参数。例如,应该返回值 (1/1) + (3/2) + (6/6) = 3.5。double sum_sequence(int n)
n
sum_sequence(3)
发现自己一直忽略的问题是整数与整数相除会产生整数类型,强制转换精度会有很大影响,在输出时分子乘上1.0将分子转换为浮点类型就可以解决这个问题。
1 int main() { 2 int a; 3 int numerator = 0; 4 int denominator = 1; 5 scanf("%d", &a); 6 for (int i = 1; i <= a; ++i) { 7 numerator += i; 8 } 9 for (int j = 1; j <= a; ++j) { 10 denominator *= j; 11 } 12 double c = numerator*1.0/denominator; 13 printf("%f",c); 14 return 0; 15 }