C# 求Sn=a+aa+aaa+...+aa...a(n个a)的值


方法一:使用一层for循环的方式

 1 using System;
 2 
 3 namespace test
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             {
10                 int i ;
11                 Console.WriteLine("请输入a的值:");
12                 int a = int.Parse(Console.ReadLine());
13                 Console.WriteLine("请输入n的值:");
14                 int n = int.Parse(Console.ReadLine());
15                 int total = 0;
16                 int sum = 0;
17                 for (i = 0; i < n; i++)
18                 {
19                     sum = sum * 10 + a;
20                     total = total + sum;
21                 }
22                 Console.WriteLine("和为:" + total);
23                 Console.ReadLine();
24                
25             }
26         }
27     }
28 }

方式二:使用递归的方式

 1 using System;
 2 
 3 namespace test
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             {
10                 Console.WriteLine("请输入a的值:");
11                 int a = int.Parse(Console.ReadLine());
12                 Console.WriteLine("请输入n的值:");
13                 int n = int.Parse(Console.ReadLine());
14                 double i, j = n;
15                 int sum = 0, total = 0;
16                 for (j = 1; j <= n; j++)
17                 {
18                     if (j == 1)
19                     {
20                         sum = a;
21                     }
22                     else
23                     {
24                         sum = sum + a * Convert.ToInt32(Math.Pow(10, (j - 1)));
25                     }
26                     total += sum;
27                 }
28                 Console.WriteLine(total);
29                 Console.ReadLine();
30             }
31         }
32     }
33 }

初次写博客的小白,如有错误,还请大佬们指正!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM