数字累加序列求和

题目描述

求 s=a+aa+aaa+aaaa+aa…a 的值,其中 a 是一个数字,例如:2+22+222+2222+22222 (此时共有5个数相加),几个数相加由键盘控制。

程序分析:关键是计算出每一项的值

输入

输入每一项的基础数字及相加的项数,中间用空格隔开

输出

输出序列和

样例输入

2 5

样例输出

24690

源代码

#include <stdio.h>
int main() {
    int sum = 0;        // 存储结果的变量
    int base, terms;    // base 为 a 的值,terms 为 n 的值
    int temp;           // 临时变量,用于计算当前项的值
    scanf("%d%d", &base, &terms);
    temp = base;          // 初始化 temp 为 a
    
    // 通过循环计算 a + aa + aaa + ...
    
    while (terms > 0) {
        sum += temp;          // 累加当前项
        base *= 10;           // base 每次左移一位(例如 2 -> 20 -> 200)
        temp += base;         // 更新 temp,使其变为下一项
        terms--;              // 减少剩余项数
    }
    printf("%d\n", sum);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值