2012-11-15 105 views
-2

我在爲三位數字做這件事情時遇到了一些麻煩。我可以爲兩位數字做這件事,但是當我向字符串TwoDigit添加if語句時,它告訴我檢測到無法訪問的代碼。這是我曾嘗試: -將三位數字轉換爲文本

{ 
    class Program 
    { 
     static string[] digitWords = 
     { "zero", "one", "two", "three", "four", 
      "five", "six", "seven", "eight", "nine", 
      "ten", "eleven", "twelve", "thirteen", "fourteen", 
      "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; 

     static string[] tenWords = 
     { "", "", "twenty", "thirty", "forty", 
      "fifty", "sixty", "seventy", "eighty", "ninety" }; 

     static string[] hundredWords = { "One-hundred", "two-hundred", 
      "three-hundred", "four-hundred", "five-hundred", "six-hundred", 
      "seven-hundred", "eight-hundred", "nine-hundred"} 

     static string TwoDigit(int num) 
     { 
      if (num < 0 || num > 99) return ""; 
      if (num < 20) return digitWords[num]; 
      if (num % 10 == 0) 
       return tenWords[num/10]; 
      else 
       return tenWords[num/10] + "-" + digitWords[num % 10]; 

      if (num % 100 == 0) 
       return digitWords[num/100] + "-" + hundredWords[num % 100]; 
      else 
       return digitWords[num/100] + "-" + hundredWords[num % 100] + "-" + digitWords[num % 100]; 
     } 

     static void Main(string[] args) 
     { 
      for (int i = 0; i <= 19; i++) 
       Console.WriteLine("{0}: {1}", i, TwoDigit(i)); 
      for (int i = 20; i <= 99; i +=7) 
       Console.WriteLine("{0}: {1}", i, TwoDigit(i)); 
      for (int i = 100; i <= 1100; i += 7) 
       Console.WriteLine("{0}: {1}", i, TwoDigit(i)); 
     } 
    } 
} 
+1

請不要將創造同樣的問題提問:[首頁](http://stackoverflow.com/questions/13352149/two-數字)[Second](http://stackoverflow.com/questions/13389624/numbers-2-to-words-two) – TheEvilPenguin

回答

0

你可能是在哪裏發生了誤差,但我可以看到的TwoDigit()後半不可達更加清晰。由於在返回之前if聲明的兩種情況,下面的代碼不可能被執行。 return語句退出該方法,並且不會執行該方法中的其他語句。這就是爲什麼它無法訪問。

你可以看到我是如何在我的文章Converting Numbers to Words中提供的代碼中做到這一點的。

0

你必須在兩個分支return碼 - 作爲結果代碼後if條件將永遠不會被執行:

if (condition) 
    { 
     return 1; 
    } 
    else 
    { 
    return 2; 
    } 
    // never will reach here 
    var i = 1; // unreachable code. 
0

對於你得到錯誤的具體問題:

你的第3如果語句總是返回一個值,那麼你將永遠達不到第四條if語句。 (記住,一旦你返回你完成該功能,其餘的代碼將不會被執行!)

此外,你可能想重新考慮你的邏輯在這裏,因爲輸入任何值> 99將只返回「」作爲最後的答案

0

我相信你可以通過在TwoDigit的是串接不同的值到它的頂部添加一個字符串,解決這個問題,然後返回在最後的newstring:

static string TwoDigit(int num) 
{ 
    string newstring = ""; 

    if (num < 0 || num > 99) return ""; 
    if (num < 20) return digitWords[num]; 
    if (num % 10 == 0) 
     newstring += tenWords[num/10]; 
    else 
     newstring += tenWords[num/10] + "-" + digitWords[num % 10]; 

    if (num % 100 == 0) 
     newstring += digitWords[num/100] + "-" + hundredWords[num % 100]; 
    else 
     newstring += digitWords[num/100] + "-" + hundredWords[num % 100] + "-" + 
       digitWords[num % 100]; 

    return newstring; 
} 

類似的東西應該工作如果我正確理解你。

發生這種情況的原因(正如其他人所說的),無論傳入什麼值,第一個if/else塊總是會退出函數。您的編譯器正在檢測到這個錯誤,並且因爲它有一個錯誤感覺你在做一些你不想做的事情。 (C#是強類型的,編譯器不允許類似於C或C++這樣的語言的許多事情,C或C++會允許這樣做,但會得到意想不到的結果和邏輯錯誤)

編輯:經過進一步的思考後,你需要改變連接數字的順序(數百個,數十個,最後一個),以使其有意義。

0

我前段時間在SO上發現了下面的代碼,並且認爲它是一個小巧的Linq解決這個問題的令人欽佩的東西。我現在找不到帖子,所以如果有人認出它,並且可以鏈接到原始解決方案,那就太好了。我不是那個可以獲得這個獎勵的人。

private static Dictionary<string, long> numberTable = 
    new Dictionary<string, long> 
    {{"zero",0},{"one",1},{"two",2},{"three",3},{"four",4}, 
    {"five",5},{"six",6},{"seven",7},{"eight",8},{"nine",9}, 
    {"ten",10},{"eleven",11},{"twelve",12},{"thirteen",13}, 
    {"fourteen",14},{"fifteen",15},{"sixteen",16}, 
    {"seventeen",17},{"eighteen",18},{"nineteen",19},{"twenty",20}, 
    {"thirty",30},{"forty",40},{"fifty",50},{"sixty",60}, 
    {"seventy",70},{"eighty",80},{"ninety",90},{"hundred",100}, 
    {"thousand",1000},{"million",1000000},{"billion",1000000000}, 
    {"trillion",1000000000000},{"quadrillion",1000000000000000}, 
    {"quintillion",1000000000000000000}}; 

    public static long ToLong(string numberString) 
    { 
     var numbers = Regex.Matches(numberString, @"\w+").Cast<Match>() 
      .Select(m => m.Value.ToLowerInvariant()) 
      .Where(v => numberTable.ContainsKey(v)) 
      .Select(v => numberTable[v]); 
     long acc = 0, total = 0L; 
     foreach (var n in numbers) 
     { 
      if (n >= 1000) 
      { 
       total += (acc * n); 
       acc = 0; 
      } 
      else if (n >= 100) 
      { 
       acc *= n; 
      } 
      else acc += n; 
     } 
     return (total + acc) * (numberString.StartsWith("minus", 
       StringComparison.InvariantCultureIgnoreCase) ? -1 : 1); 
    } 
0

剛看到這個野趣解決方案here

namespace NumToText 
{ 
    static class NumberToText 
    { 
     private static string[] _ones = 
     { 
      "zero", 
      "one", 
      "two", 
      "three", 
      "four", 
      "five", 
      "six", 
      "seven", 
      "eight", 
      "nine" 
     }; 

     private static string[] _teens = 
     { 
      "ten", 
      "eleven", 
      "twelve", 
      "thirteen", 
      "fourteen", 
      "fifteen", 
      "sixteen", 
      "seventeen", 
      "eighteen", 
      "nineteen" 
     }; 

     private static string[] _tens = 
     { 
      "", 
      "ten", 
      "twenty", 
      "thirty", 
      "forty", 
      "fifty", 
      "sixty", 
      "seventy", 
      "eighty", 
      "ninety" 
     }; 

     // US Nnumbering: 
     private static string[] _thousands = 
     { 
      "", 
      "thousand", 
      "million", 
      "billion", 
      "trillion", 
      "quadrillion" 
     }; 

     /// <summary> 
     /// Converts a numeric value to words suitable for the portion of 
     /// a check that writes out the amount. 
     /// </summary> 
     /// <param name="value">Value to be converted</param> 
     /// <returns></returns> 
     public static string Convert(decimal value) 
     { 
      string digits, temp; 
      bool showThousands = false; 
      bool allZeros = true; 

      // Use StringBuilder to build result 
      StringBuilder builder = new StringBuilder(); 
      // Convert integer portion of value to string 
      digits = ((long)value).ToString(); 
      // Traverse characters in reverse order 
      for (int i = digits.Length - 1; i >= 0; i--) 
      { 
       int ndigit = (int)(digits[i] - '0'); 
       int column = (digits.Length - (i + 1)); 

       // Determine if ones, tens, or hundreds column 
       switch (column % 3) 
       { 
        case 0:  // Ones position 
         showThousands = true; 
         if (i == 0) 
         { 
          // First digit in number (last in loop) 
          temp = String.Format("{0} ", _ones[ndigit]); 
         } 
         else if (digits[i - 1] == '1') 
         { 
          // This digit is part of "teen" value 
          temp = String.Format("{0} ", _teens[ndigit]); 
          // Skip tens position 
          i--; 
         } 
         else if (ndigit != 0) 
         { 
          // Any non-zero digit 
          temp = String.Format("{0} ", _ones[ndigit]); 
         } 
         else 
         { 
          // This digit is zero. If digit in tens and hundreds 
          // column are also zero, don't show "thousands" 
          temp = String.Empty; 
          // Test for non-zero digit in this grouping 
          if (digits[i - 1] != '0' || (i > 1 && digits[i - 2] != '0')) 
           showThousands = true; 
          else 
           showThousands = false; 
         } 

         // Show "thousands" if non-zero in grouping 
         if (showThousands) 
         { 
          if (column > 0) 
          { 
           temp = String.Format("{0}{1}{2}", 
            temp, 
            _thousands[column/3], 
            allZeros ? " " : ", "); 
          } 
          // Indicate non-zero digit encountered 
          allZeros = false; 
         } 
         builder.Insert(0, temp); 
         break; 

        case 1:  // Tens column 
         if (ndigit > 0) 
         { 
          temp = String.Format("{0}{1}", 
           _tens[ndigit], 
           (digits[i + 1] != '0') ? "-" : " "); 
          builder.Insert(0, temp); 
         } 
         break; 

        case 2:  // Hundreds column 
         if (ndigit > 0) 
         { 
          temp = String.Format("{0} hundred ", _ones[ndigit]); 
          builder.Insert(0, temp); 
         } 
         break; 
       } 
      } 

      // Append fractional portion/cents 
      builder.AppendFormat("and {0:00}/100", (value - (long)value) * 100); 

      // Capitalize first letter 
      return String.Format("{0}{1}", 
       Char.ToUpper(builder[0]), 
       builder.ToString(1, builder.Length - 1)); 
     } 
    } 
}