我做了一个foreach循环,它将接受用户的输入并减去同一行上的两个数字,我希望它能打印出任何两个数字之间的差,但它没有。相反,当我运行代码并输入数字时,它打印了一个不同的答案,这对我来说没有意义。我对c#有点陌生,所以我只是在尝试一些东西,但如果有人知道我的代码有什么问题,请帮我找出它有什么问题。谢谢!
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
您的answer
最初将是0
。因此,当你做answer -=
时,你从零减去右手部位(例如5
(,这将导致负面结果。我想你需要为你的answer
:分配第一个操作员
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
var parts = sequence.Split('-');
answer = parts[0];
for(int i = 1; i < parts.Length; i++)
{
answer -= double.Parse(parts[i]);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
当然,您应该检查parts
中是否至少有两个元素。
假设您想要5而不是-15?
你需要用第一个数字初始化答案的值,而不是从零开始减去所有的值。
bool init;
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
if (!init) {
answer = double.Parse(operation);
init = true;
}
else
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}