2025年4月10日 星期四 乙巳(蛇)年 正月十一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Java

Java求s=a+aa+aaa+aaaa+aa...a的值

时间:10-11来源:作者:点击数:34

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

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

程序设计:

  • import java.io.*;
  • public class Sumloop {
  • public static void main(String[] args) throws IOException
  • {
  • int s=0;
  • String output="";
  • BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
  • System.out.println("请输入a的值");
  • String input =stadin.readLine();
  • for(int i =1;i<=Integer.parseInt(input);i++)
  • {
  • output+=input;
  • int a=Integer.parseInt(output);
  • s+=a;
  • }
  • System.out.println(s);
  • }
  • }

另解:

  • import java.io.*;
  • public class Sumloop {
  • public static void main(String[] args) throws IOException
  • {
  • int s=0;
  • int n;
  • int t=0;
  • BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
  • String input = stadin.readLine();
  • n=Integer.parseInt(input);
  • for(int i=1;i<=n;i++){
  • t=t*10+n;
  • s=s+t;
  • System.out.println(t);
  • }
  • System.out.println(s);
  • }
  • }

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门