简单的乘法
本文关键字:简单 | 更新日期: 2023-09-27 17:50:35
我们开门见山吧。我编写了下面的代码来将两个数字相乘,结果它"吃掉"了我的0 !对于不涉及乘积(p)等于0的情况,它似乎工作得很好。在示例示例中,它只是打印"5"而不是期望的"500"。如果有人愿意解释一下发生了什么,我会非常感激。:)
using System;
class Program
{
static void Main()
{
Console.WriteLine(smallNumBigNumProduct("5", "100"));
}
static string smallNumBigNumProduct(string s, string b)
{
int l = s.Length;
int f = int.Parse(s); // factor
int c = 0; // carry
string r = ""; // result
int p; // product
while(l-- > 0)
{
p = (Convert.ToInt32(b[l]) - 48) * f;
p += c;
if (p > 9)
{
r = Convert.ToString(p % 10) + r;
c = p / 10;
}
else
r = Convert.ToString(p) + r;
}
if (c > 0)
{
r = Convert.ToString(c) + r;
}
return r;
}
}
你的问题是:
int l = s.Length;
...
while(l-- > 0)
您将l
变量设置为短字符串的长度,然后在while
循环中预减量。
简而言之,你的循环执行的次数并不像你想象的那么多。不应该将l
变量设置为b
字符串的长度吗?
如何:
public static string smallNumBigNumProduct(string a, string b)
{
// NOTE no error checking for bad input or possible overflow...
int num1 = Convert.ToInt32(a);
int num2 = Convert.ToInt32(b);
return ((num1*num2).ToString());
}
如果你使用的是。net 4.0(多亏了Gabe的提示更新),那就更好了:
public static string smallNumBigNumProduct(string a, string b)
{
// NOTE no error checking for bad input or possible overflow...
BigInteger num1 = BigInteger.Zero;
BigInteger num2 = BigInteger.Zero;
bool convert1 = BigInteger.TryParse(a, out num1);
bool convert2 = BigInteger.TryParse(b, out num2);
return (convert1 && convert2) ? (num1*num2).ToString() : "Unable to convert";
}