当前位置:   article > 正文

C语言:分别用while, do-while, for语句编程,求数列前20项之和 2/1, 3/2, 5/3......_用 while 语句和 do-while 语句分别设计程序,计算自然数列 1,2,3……,n 的和,

用 while 语句和 do-while 语句分别设计程序,计算自然数列 1,2,3……,n 的和,

C语言:分别用while, do-while, for语句编程,求数列前20项之和 2/1, 3/2, 5/3…

while写法:

#include<stdio.h>

int main()
{
    double sum=0, a=2, b=1, c, term;
    int i=1;
    
    while (i<=20)
    {
        term = a/b;
        sum = sum + term;
        c = a+b;
        b = a;
        a = c;
        i++;
    }
    
    printf("The sum is: %.2f\n",sum);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

do-while写法:

#include<stdio.h>

int main()
{
    double sum=0, a=2, b=1, c, term;
    int i=1;
    
    do
    {
        term = a/b;
        sum = sum + term;
        c = a+b;
        b = a;
        a = c;
        i++;
    } while (i<=20);

    printf("The sum is: %.2f\n",sum);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

for写法:

#include<stdio.h>

int main()
{
    double sum=0, a=2, b=1, c, term;
    int i;
    
    for(i=1; i<=20; i++)
    {
        term = a/b;
        sum = sum + term;
        c = a+b;
        b = a;
        a = c;
    }
    
    printf("The sum is: %.2f\n",sum);
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/774271
推荐阅读
相关标签
  

闽ICP备14008679号