Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

后端 未结 8 565
名媛妹妹
名媛妹妹 2021-02-01 11:37

Write C/C++/Java code to convert given number into words.

eg:- Input: 1234

Output: One thousand two hundred thirty-four.

Input: 10

Output: Ten

8条回答
  •  心在旅途
    2021-02-01 11:58

    Works for any number from 0 to 999999999.

    This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

    #include 
    using namespace std;
    int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
    long input, nFake = 0;
    const char ones[][20] = {"",       "one",       "two",      "three",
                             "four",    "five",      "six",      "seven",
                             "eight",   "nine",      "ten",      "eleven",
                             "twelve",  "thirteen",  "fourteen", "fifteen",
                             "sixteen", "seventeen", "eighteen", "nineteen"};
    const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                             "fifty", "sixty", "seventy", "eighty", "ninety"};
    void convert(int funcVar);
    int main() {
      cout << "Enter the number:";
      cin >> input;
      nFake = input;
      buffer = 0;
      while (nFake) {
        part[buffer] = nFake % 1000;
        nFake /= 1000;
        buffer++;
      }
      if (buffer == 0) {
        cout << "Zero.";
      } else if (buffer == 1) {
        convert(part[0]);
      } else if (buffer == 2) {
        convert(part[1]);
        cout << " thousand,";
        convert(part[0]);
      } else {
        convert(part[2]);
        cout << " million,";
    
        if (part[1]) {
          convert(part[1]);
          cout << " thousand,";
        } else {
          cout << "";
        }
        convert(part[0]);
      }
      system("pause");
      return (0);
    }
    
    void convert(int funcVar) {
      buffer = 0;
      if (funcVar >= 100) {
        a = funcVar / 100;
        b = funcVar % 100;
        if (b)
          cout << " " << ones[a] << " hundred and";
        else
          cout << " " << ones[a] << " hundred ";
        if (b < 20)
          cout << " " << ones[b];
        else {
          c = b / 10;
          cout << " " << tens[c];
          d = b % 10;
          cout << " " << ones[d];
        }
      } else {
        b = funcVar;
        if (b < 20)
          cout << ones[b];
        else {
          c = b / 10;
          cout << tens[c];
          d = b % 10;
          cout << " " << ones[d];
        }
      }
    }
    

提交回复
热议问题