AI智能
改变未来

C# 输入一个正整数N,判断N是奇数还是偶数,输出1~N的奇数和或是偶数和,三种不同方法分别实现

[code]using System;namespace _2_2 {class Program {static void Main(string[] args) {Console.WriteLine(\"请输入一个正整数N\");string str = Console.ReadLine();int number =int.Parse(str);bool isOdd = false;int sum = 0;isOdd = OddOrEven1(number, out sum);AnswerFormat(isOdd, number, sum);isOdd = OddOrEven2(number, out sum);AnswerFormat(isOdd, number, sum);isOdd = OddOrEven3(number, out sum);AnswerFormat(isOdd, number, sum);Console.ReadKey();}/// <summary>/// 1.判断奇数偶数并求和:循环方式/// </summary>public static bool OddOrEven1(int number,out int sum) {bool isOdd = (number % 2) > 0;sum = 0;//初始值根据如果是奇数取1,否则取2for (int start = isOdd ? 1 : 2; start <= number; start+=2) {sum += start;}return isOdd;}/// <summary>/// 2.判断奇数偶数并求和:直接计算方式/// </summary>public static bool OddOrEven2(int number, out int sum) {bool isOdd = (number % 2) > 0;if (isOdd) {sum = (1 + number) / 2 * (number + 1) / 2;} else {sum = (2 + number) * number / 4;}return isOdd;}/// <summary>/// 3.判断奇数偶数并求和:递归计算方式/// </summary>public static bool OddOrEven3(int number, out int sum) {sum = OddOrEvent3(number);return number % 2 > 0;}/// <summary>/// 递归计算方法/// </summary>private static int OddOrEvent3(int number,int currentSum = 0) {currentSum += number;if (number <= 1) return currentSum;return OddOrEvent3(number -= 2, currentSum);}public static void AnswerFormat(bool isOdd,int number,int sum) {if (isOdd) {Console.WriteLine($\"{number} 是奇数,小于等于{number}的所有奇数的和为:{sum}\");} else {Console.WriteLine($\"{number} 是偶数,小于等于{number}的所有偶数的和为:{sum}\");}}}}

运行结果

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# 输入一个正整数N,判断N是奇数还是偶数,输出1~N的奇数和或是偶数和,三种不同方法分别实现