a+aa+aaa+.......+aaaaaaaaa其中a为1至9之中的一个数,项数也要可以指定。(笔记-002)

题目:a+aa+aaa+.......+aaaaaaaaa,其中a为1至9之中的一个数,项数也要可以指定。


代码

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入a:");
        int a = sc.nextInt();
        System.out.println("请输入项数:");
        int count = sc.nextInt();
        int res = 0;
        int temp = 0;
        for (int i = 0; i < count; i++) {
            if (i == 0) {
                temp = a;
                res += temp;
            } else {
                temp = temp * 10 + a;
                res += temp;
            }
        }
        System.out.println("结果:" + res);
    }
}

自我理解如下:

public class Main {
    public static void main(String[] args) {



        Scanner sc = new Scanner(System.in);
     
  System.out.println("请输入a:");
        int a = sc.nextInt();
       
System.out.println("请输入项数:");
        int count = sc.nextInt();

这一段是java的输入函数,可以看作者的另一篇笔记。

判断是否为闰年及输入函数的理解(新手练习及笔记整理)-001-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/weixin_74710173/article/details/138122763?spm=1001.2014.3001.5501



        int res = 0;                                                         //定义一个变量作为总和
        int temp = 0;                                                      //定义一个变量作为当前值,便于计算
        for (int i = 0; i < count; i++) {
            if (i == 0) {                                                      //当项数为0时,算式总和为a。
                temp = a;
                res += temp;
            } else {                                                           //当项数不为0时,将每一项加起来
                temp = temp * 10 + a;                               //temp计算的是当前项的值。

                res += temp;

            }   

设a=1,i=1时,temp=1*10+1=11;

             i=2时,temp=11*10+1=111;

             ......

如此,便可以一直计算,直到将给出的项数相加完,得出答案。


           
        }
        System.out.println("结果:" + res);
    }
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值