用控制台应用程序实现下列功能:从键盘接收-一个大于100 的整数,然后分别输出该整数每一位的值,并输出这些位相加的结果。要求分别用字符提取法和整数整除法实现。字符提取法是指先将整数转换为字符串,然后依次取字符串中的每个字符,再将每个字符转换为整数求和。整数整除法是指利用取整和求余数的办法求每位的值, 再求这些位的和。
using System; namespace Hch_ConsoleApp_02 { class Program { static void Main(string[] args) { Console.WriteLine("姓名:胡长浩 \t 学号:1924240009"); Console.Write("请输入一个大于一百的整数:"); string input = Console.ReadLine(); Console.WriteLine("该整数共有{0}位",input.Length); CharExtract(input); NumberCut(input); } private static void CharExtract(string str) { int sum = 0; Console.Write("字符提取法:每一位的值为"); try { for (int i = 0; i < str.Length; i++) { Console.Write(str[i] + "、"); //sum += Convert.ToInt32((char)str[i]); //sum += Int32.Parse(); sum += (int) Char.GetNumericValue(str[i]); } Console.WriteLine("这些位之和位{0}", sum); } catch { Console.WriteLine("字符串格式有误,无法转换位整数"); } } private static void NumberCut(string Number) { int sum = 0; int theUnit; //int[] record = new int [Number.Length]; int[] record = new int[20]; try { int number = int.Parse(Number); for (int i = 0; i < Number.Length; i++) { theUnit = number % 10; number = number / 10; record[i] = theUnit; //record[i] = theUnit; }; Console.Write("字符提取法:每一位的值位"); for (int i=Number.Length-1; i >= 0; i--) { sum += record[i]; Console.Write(record[i]+"、"); } Console.WriteLine("这些位之和位{0}",sum); } catch { Console.WriteLine("字符串格式有误,无法转换位整数"); } } } }