C# 如何实现函数内数组求和、顾客数据录入及素数判断功能
C# 控制台程序实现方案
修复点说明
- 调整
sumOfPrice函数参数定义,支持接收3个顾客数据数组作为入参 - 新增字符串格式价格到数值的转换逻辑,解决无法正确累加求和的问题
- 修复素数判断逻辑,原逻辑仅判断是否为偶数,现已覆盖所有素数判断的边界场景
- 调整Main方法逻辑,按需求调用3次
inputData函数录入3名顾客的完整数据
using System; namespace 顾客消费统计 { class Program { // 录入单名顾客数据 public static string [] inputData() { Console.WriteLine("请输入顾客的名字:"); string FirstName = Console.ReadLine(); Console.WriteLine("请输入顾客的姓氏:"); string LastName = Console.ReadLine(); Console.WriteLine("请输入购买的商品名称:"); string product = Console.ReadLine(); Console.WriteLine("请输入商品价格:"); string price = Console.ReadLine(); string[] info = new string[4] { FirstName, LastName, product, price }; return info; } // 计算3名顾客总消费金额 public static int sumOfPrice(string[] customer1, string[] customer2, string[] customer3) { int total = 0; // 依次转换3名顾客的价格为整数后累加 total += Convert.ToInt32(customer1[3]); total += Convert.ToInt32(customer2[3]); total += Convert.ToInt32(customer3[3]); return total; } // 判断总金额是否为素数 public static void isTotalCostPrime(int total) { // 小于等于1的数都不是素数 if (total <= 1) { Console.WriteLine("Customers won't get the price"); return; } // 2是唯一的偶素数 if (total == 2) { Console.WriteLine("Customers win the Price"); return; } // 大于2的偶数直接排除 if (total % 2 == 0) { Console.WriteLine("Customers won't get the price"); return; } // 遍历到平方根即可判断,减少循环次数 for (int i = 3; i <= Math.Sqrt(total); i += 2) { if (total % i == 0) { Console.WriteLine("Customers won't get the price"); return; } } Console.WriteLine("Customers win the Price"); } public static void Main (string[] args) { // 调用3次录入函数,获取3名顾客数据 string[] customer1 = inputData(); string[] customer2 = inputData(); string[] customer3 = inputData(); // 计算总金额 int totalPrice = sumOfPrice(customer1, customer2, customer3); Console.WriteLine($"3名顾客总消费金额为:{totalPrice}"); // 判断是否为素数并输出结果 isTotalCostPrime(totalPrice); } } }
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

