小宝的第二章2

/* 定义和调用求阶乘函数生成阶乘表 */
#include<stdio.h>
double fact(int n);
int main(void)
{
    int i,n;
    double result;

    printf("Enter n:");
    scanf_s("%d",&n);
    for(i=0;i<=n;i++){
        result=fact(i);
        printf("%d!=%.0f\n",i,result);
    }

    return 0;
}

double fact(int n)
{
    int i;
    double product;

    product=1;
    for(i=1;i<=n,i++;){
        product=product*i;
    }

    return product;
}

 

/* 调用幂函数pow()生成乘方表 */
#include<stdio.h>
#include<math.h>
int main(void)
{
    int i,n;
    double power;

    printf("Enter n:");
    scanf_s("%d",&n);
    for(i=0;i<=n;i++){
        power=pow((double)2,i);
        printf("pow(2,%d)=%.0f\n",i,power);
    }

    return 0;
}

 

/* 输入一个正整数n, 求n! */
#include<stdio.h>
int main(void)
{
    int i,n;
    double product;

    printf("Enter n:");
    scanf_s("%d",&n);
    product=1;
    for(i=1;i<=n;i++){
        product=product*i;
    }
    printf("product=%.0f\n",product);

    return 0;
}

 

/* 计算1-1/3+1/5-1/7+… 共n项之和 */
#include<stdio.h>
int main(void)
{
    int denominator,flag,i,n;
    double item,sum;

    printf("Enter n:");
    scanf_s("%d",&n);
    flag=1;
    denominator=1;
    sum=0;
    for(i=1;i<=n;i++){
        item=flag*1.0/denominator;
        sum=sum+item;
        flag=-flag;
        denominator=denominator+2;
    }
    printf("sum=%f\n",sum);

    return 0;
}

 

/* 计算 1+2+3+…+n */
#include<stdio.h>
int main(void)
{
    int i,n,sum;

    printf("Enter n:");
    scanf_s("%d",&n);
    sum=0;
    for(i=1;i<=n;i++){
        sum=sum+i;
    }

    printf("Sum of numbers from 1 to %d is %d is %d\n",n,sum);

    return 0;
}

 

posted @ 2013-10-03 18:04  xiaobao123  阅读(132)  评论(0编辑  收藏  举报