首頁 >後端開發 >C#.Net教程 >將數字轉換為單字的 C# 程序

將數字轉換為單字的 C# 程序

王林
王林轉載
2023-08-29 20:49:09851瀏覽

将数字转换为单词的 C# 程序

首先,宣告從0 到9 的單字-

// words for every digits from 0 to 9
string[] digits_words = { "zero", "one", "two",
   "three", "four", "five",
   "six", "seven", "eight",
   "nine"
};

以下是要轉換為單字的數字-

// number to be converted into words
val = 4677;
Console.WriteLine("Number: " + val);

使用循環檢查給定數字中的每個數字並將其轉換為單字-

do {
   next = val % 10;
   a[num_digits] = next;
   num_digits++;
   val = val / 10;
} while(val > 0);

範例

您可以嘗試執行以下程式碼將數字轉換為單字。

現場示範

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int val, next, num_digits;
         int[] a = new int[10];
         // words for every digits from 0 to 9
         string[] digits_words = {
            "zero",
            "one",
            "two",
            "three",
            "four",
            "five",
            "six",
            "seven",
            "eight",
            "nine"
         };
         // number to be converted into words
         val = 4677;
         Console.WriteLine("Number: " + val);
         Console.Write("Number (words): ");
         next = 0;
         num_digits = 0;
         do {
            next = val % 10;
            a[num_digits] = next;
            num_digits++;
            val = val / 10;
         } while (val > 0);
         num_digits--;
         for (; num_digits >= 0; num_digits--)
         Console.Write(digits_words[a[num_digits]] + " ");
         Console.ReadLine();
      }
   }
}

輸出

Number: 4677
Number (words): four six seven seven 

以上是將數字轉換為單字的 C# 程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除