0

我正在编写一个将数字转换为文本的 c++ 程序。

我遇到了两个问题(编辑:现在只有一个):

  • 第一个问题是程序只写出正确的 1-19 数字,从 20-99 的所有数字,例如当我写 34 时,我得到的答案是 30,而不是应该的 34。三十之后它只是出现错误并且程序关闭。[问题已解决]

  • 第二个问题是我希望我可以写 0-999 之间的数字而不仅仅是 99 但我不知道该怎么做

     #include <iostream>
     #include <string>
     using namespace std;
    
    
    int main()
      {
     int num, Ldight, Rdight;
    
        string ones[] = {"zero", "one", "two", "three", "four", 
                "five","six", "seven", "eight", "nine", "ten",
                "eleven", "twelve", "thirteen", "fourteen",  "fifteen",
                "sixteen", "seventeen", "eighteen", "nineteen"};
    
    string tens[] = {"twenty","thirty","fourty","fifty", "sixty","seventy","eighty", "ninety"};
    
    
        cout << "Pick a number between 1-99: ";
        cin >> num;
    
          if(num <= 0)
              {
            cout << "ERROR!" << endl;
              }
    
       else if (num >= 0 && num <= 19)
              {
    cout << "Your number is: " << ones[Rdight] ;
              }
    
       else if (num >=20 && num <=99)
        {
    Rdight = num % 10;
    Ldight = num / 10;
    
    cout << "Your number is: " << tens[Ldight - 2] << ones[Rdight];
         }
    
    return 0;
    }
    
4

4 回答 4

3

你应该改变这个:

cout << "Your number is: " << tens[Ldight - 2] << ones[num];

cout << "Your number is: " << tens[Ldight - 2] << ones[Rdight];

您计算一个从未使用过的值。并且在上面的行中,onesnum 访问索引越界。

于 2013-02-06T15:38:50.687 回答
1

For your first question, your problem is in this line:

cout << "Your number is: " << tens[Ldight - 2] << ones[num];

You are using the wrong variable, although correctly calculating the value in the lines just above. I'm not telling you how to fix it, as you are the one learning programming, and you need to learn how to spot this type of problem.

[I personally would add two dummy fields to "tens", so as you don't have to do -2 as well - that's a small price to pay].

As for your second problem, you'll have to consider how you go about saying it, and you'll probably come up with something... It's not VERY different from solving single digits, let's say. If you need more than about half a dozen or so lines, you are solving it wrong.

And once you have solved hundreds, it will be very trivial to add numbers up to millions, and even much further, with just a few lines of extra code.

于 2013-02-06T15:41:10.277 回答
0

使用以下行:

cout << "你的号码是:" << tens[Ldigit - 2] << one[ Rdigit-1 ];

one[] 中不需要元素“零”,因为当 i/p <= 0 时输出为错误,因此删除元素“零”

于 2013-02-06T16:03:55.120 回答
-1

You could try by splitting user input to 2 pieces. If user input is : 55 you split it in 5 and 5 and then print

tens[5] + ones[5]

That would be much better solution. You will delete all those if-s that can cause problems

于 2013-02-06T15:41:08.357 回答