我认为我的逻辑是正确的但是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';
}
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}
答案 2 :(得分:1)
问题是你没有在“getMsd”函数中检查1到9的数字。但是,我不建议您使用此逻辑,因为它不可扩展。我的意思是你不能使用这个代码与6位数字
答案 3 :(得分: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;
}
答案 4 :(得分: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时,此逻辑工作正常。它将永远不会打印&#34;零&#34;因为当你减去num - b1
205-200
时,你会得到5。
就您的计划而言,您滥用while
条件,因为根据您的条件while (num3 > 0)
,此条件永远不会打印最后一位数字。
希望你能指出我的意见。 :)
答案 5 :(得分: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;
}