我有这段代码,这是我目前正在制作的计算器的一部分。
class Program
{
static void Main(string[] args)
{
string a = "6-3";/*This is supposed to be entered in a textbox by a user*/
int b = a.IndexOf(("-"));
string c = a.Substring(0, b);
int num1 = Convert.ToInt32(c);
int b2 = a.IndexOf(("-"));
string c2 = a.Substring(b);
int num2 = Convert.ToInt32(c2);
if(a.Contains("-"))
{
int an = num1 - num2;
string ans = Convert.ToString(an);
Console.WriteLine(ans);
}
}
}问题是,这样做的结果是9而不是3,这应该是输出。如果我尝试使用完全相同的除法或乘法代码,程序就会崩溃。虽然看起来很奇怪,但是代码与加法完美地工作在一起。有什么帮助吗?
发布于 2017-02-09 22:24:53
因为这句话:
string c2 = a.Substring(b);c2等于"-3“,因此转换为-3。6 - -3是9岁。
将行更改为:
string c2 = a.Substring(b + 1);还有许多其他的问题,代码需要进行严肃的重构,但这有点偏离主题。
发布于 2017-02-09 22:24:20
当您子字符串c2时,b是1。"6-3".Substring(1)将返回-3。子字符串参数首先输入的是向前移动的距离。您需要移动索引+1以通过操作符。
这使得你的数学题成为6 - - 3
发布于 2017-02-09 22:25:35
这是因为您使用的是-3,而不是3。string c2 = a.Substring(b);应该是string c2 = a.Substring(b+1);
这方面的一个较短版本是:
if(a.Contains("-"))
{
string[] nums = a.split('-')
Console.WriteLine( ((int)nums[0]) - ((int)nums[1]) )
}https://stackoverflow.com/questions/42147969
复制相似问题