2011-04-17 101 views
3

让我们直接点。我做了下面的代码来乘以两个数字,它“吃”我的零点!对于不涉及产品(p)等于零的情况,它似乎工作正常。在示例中,它仅打印“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; 
    } 
} 
+0

我不明白你的意思。 :p – Codetester 2011-04-17 06:04:16

+0

哎呀...我刚看到我的错误。 – Codetester 2011-04-17 06:07:54

+3

一个字母的变量名称会伤害你*和*我。 – arcain 2011-04-17 06:16:06

回答

5

这里是你的问题:

int l = s.Length; 

... 

while(l-- > 0) 

您正在设置您的l可变长度的字符串,然后在你的while循环中预先递减它。

简而言之,您的循环不会执行您认为它的次数。不应将l变量设置为b字符串的长度吗?

无论如何,这看起来像一个长期和容易出错的方式来做到这一点。为什么不简单地将输入字符串转换为整数并直接返回产品?

+0

我已经修复了这个错误!我打算用b,而不是l。轻微忽略!谢谢!我这样做的原因是能够将一个小数字与一个有几十个数字的数字相乘。 – Codetester 2011-04-17 06:16:31

+2

因此,在.NET 4.0中引入的[BigInteger](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx)无法为您工作? – Oded 2011-04-17 06:17:48

+0

我使用这个SPOJ问题,不知道我是否可以在那边使用BigInteger。 – Codetester 2011-04-17 06:27:39

4

如何:

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"; 
} 
+0

你真的认为只有'Convert.ToInt32'才能实现名称中带有“BigNum”的函数吗?我的意思是,你至少要使用'long'或'decimal'。没有提到哪一个,即使'BigInteger'解决方案因为在进行乘法之前转换为'Int64'而被破坏。 – Gabe 2011-04-17 06:40:01

+0

@加贝:好点。 – 2011-04-17 06:54:40