棋和麦粒问题(C语言回调函数实现)

/*
    有一个棋盘,棋盘有64个格子,编号从0~63;
    从编号0开始,每个格子放麦粒(2^n)个;
    放到第i个格子时,当前格子的麦粒为(2^i)+(前面格子放的麦粒的总和);
*/

#include<stdio.h>

#define N 63

long long store(int n) {
    if (n == 0)
        return 1;
    return n = 2 * store(n - 1);

//每个格子存放的麦粒数为(2^n)个,每次回调函数进行计算。
}

long long summation(int m) {
    if (m == 0)
        return store(0);
    return store(m - 1) + summation(m - 1);

//当前格子存放的麦粒数为前面(m-1)个格子存放的麦粒数之和加上当前格子的(2^i)个麦粒。
}

//如果不使用long long数据类型的函数,会在计算到后面的数字时,出现数据存储越界,导致数据为0;

//回调函数在使用时一定设置临界条件退出回调,不然会导致程序出现死循环。

int main() {


    int i;
    int j ;
    printf("Please enter what the ith cell is:\n");
    scanf("%d", &i);
    printf("The designated i grid that you enter is %d:\n",i);
    store(i);
    for (j = 0; j < i-1; j++) {
        printf("The number of grains stored on the %d board is %lld\n", j+1, store(j));
    }
    summation(i);
    printf("So the number of grains stored in the i(%d) cell is %lld\n", i, summation(i)-1);
    return 0;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值