我的任务有点麻烦。用户输入一个范围(2个整数)太过迅速,然后使用下面的格式显示范围内的方程式。
示例:
Enter minimum integer: 3
Enter maximum integer: 7
All: 3 + 4 + 5 + 6 + 7 = 25
Even: 4 + 6 = 10
Odd: 3 + 5 + 7 = 15
不要求整个解决方案,只是一些循环格式化问题。任何帮助将不胜感激。
Console.Write("Enter minimum integer: ");
string min = Console.ReadLine();
Console.Write("Enter maximum integer: ");
string max = Console.ReadLine();
int min32 = int.Parse(min);
int max32 = int.Parse(max);
for (int i = min32; i <= max32; i++)
Console.Write(i + " + ");
答案 0 :(得分:1)
最简单的方法是开始在控制台中输出数字,始终检查这是否是最后输出的数字(如果是这种情况,请不要在数字后打印+
。)
Console.Write("All: ");
int sum = 0;
for (int i = min32; i <= max32; i++)
{
if(i != max32) //Only add " + " after the number if this is not the end of the for loop
Console.Write(i + " + ");
else
Console.Write(i);
sum += i;
}
Console.WriteLine(" = " + sum);
//Outputs for min32 = 3 and max32 = 7:
//3 + 4 + 5 + 6 + 7 = 25
奖金回合:从IEnumerable<int>
返回的Enumerable.Range()
的LINQ查询,使用一些Where
语句进行过滤,并使用string.Join()
进行连接:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write("Min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Max: ");
int max = int.Parse(Console.ReadLine());
var sequence = Enumerable.Range(min, max - min + 1);
string all = "All: " + string.Join(" + ", sequence);
string even = "Even: " + string.Join(" + ", sequence.Where(a => a % 2 == 0));
string odd = "Odd: " + string.Join(" + ", sequence.Where(a => a % 2 == 1));
Console.WriteLine(all + " = " + sequence.Sum());
Console.WriteLine(even + " = " + sequence.Where(a => a % 2 == 0).Sum());
Console.WriteLine(odd + " = " + sequence.Where(a => a % 2 == 1).Sum());
}
}
答案 1 :(得分:0)
也许为每个数字集合保留一个字符串。添加到总计时,还会将数字附加到字符串。另一个选项可能是字符串列表中的string.Join(),使用&#34; +&#34;作为分隔符。
循环结束后,打印已连接的列表以及相应的总和。