-1

我认为我的逻辑是正确的,但是 while 无限循环,输出为零。这是我的代码:

int currentMSD, currentNum = num;
if (currentNum >= 0 && currentNum < 100) {
    currentMSD = 10;
} else if (currentNum >= 100 && currentNum < 1000) {
    b1 = b * msd;
    b2 = num3 - b1;
    num3 = b2;
    switch(b) {
        case 1:
            cout << "one ";
            break;
        case 2:
            cout << "two ";
            cout << "five ";
            break;
        case 6:
            cout << "six ";
            break;
        case 9:
            cout << "nine ";
            break;
        case 0:
            cout << "zero ";
          break;
        }
    }
    cout << '\n';
}
4

6 回答 6

1

您期望 250 之类的输出是什么类型的?“二五零”?

这是一个简单的例子:

#include <iostream>

const char* nums[] = {"zero", "one", "two", "three", "four", 
                      "five", "six", "seven", "eight", "nine"};

void getMSD(unsigned int num)
{
    unsigned int remainder = num % 10;
    unsigned int result = num / 10;

    if(result > 0)
        getMSD(result);

    std::cout << nums[remainder] << " ";
}

int main()
{
    getMSD(125); //prints "one two five"

    return 0;
}
于 2012-07-10T04:28:43.897 回答
1

在您的getMSD函数中,您需要检查个位:

int getMSD(int num) {
    int currentMSD, currentNum = num;

    if (currentNum < 10) {
        currentMSD = 1;
    } else if (currentNum >= 10 && currentNum < 100) {
        currentMSD = 10;
    } else if (currentNum >= 100 && currentNum < 1000) {
        currentMSD = 100;
    } else if (currentNum >= 1000 && currentNum < 10000) {
        currentMSD = 1000;
    }
    return currentMSD;
}
于 2012-07-10T04:33:42.123 回答
1

问题是您没有在“getMsd”函数中检查 1 - 9 的数字。但是,我不建议您使用此逻辑,因为它不可扩展。我的意思是您不能将此代码用于 6 位数字

于 2012-07-10T04:36:00.340 回答
0

getMSD()功能有问题。用这个新的替换它

int getMSD(int num) {

int currentMSD = 1, currentNum = num;

if (currentNum >= 10 && currentNum < 100)
{
    currentMSD = 10;
}
else if (currentNum >= 100 && currentNum < 1000)
{
    currentMSD = 100;
}
else if (currentNum >= 1000 && currentNum < 10000)
{
    currentMSD = 1000;
}
return currentMSD;
}
于 2012-07-10T04:47:18.473 回答
0

你犯了一个逻辑错误。根据您的逻辑,您有 250 作为输入,

msd = 100 , then b = 250/100 = 2.5 = 2 which should output 'two'
b1 = msd * b = 100 * 2 = 200
b2 = num - b1 = 250 - 200 = 50
num = b2 = 50
repeat
msd = 10, then b = 50/10 = 5 which should then output 'five'
b1 = msd * b = 50
b2 = num - b1 = 50 - 50 = 0

如果输入为 250,但当您的输入为 205 时,此逻辑工作正常,它永远不会打印“零”,因为当您减去时,num - b1 205-200您将得到 5。

就您的程序而言,您正在滥用while条件,因为根据您的条件,while (num3 > 0)此条件将永远不会打印最后一位。

希望你能明白我的意思。:)

于 2012-07-10T05:16:21.533 回答
0

做更多控制(美化):

int getMSD(const int& num) {
   int currentMSD = 1;
   const int N = 3;  
   for(int j = 1, i = 1; j != N; ++j, i * 10) {
      if(num >= 10 * i && num < 100 * i) {
          currentMSD = 10 * i;
       }
   }          
   return currentMSD;
} 
于 2014-12-18T09:46:56.353 回答