我让它显示了红利,这样人们就可以毫不费力地破译代码。它工作了一次,但后来我不知道我做了什么让它停止工作。它适用于正整数。它应该显示与用户输入相关的数字。
#include <iostream> // Necessary header
using namespace std;
int main()
{
signed int Input, Divisor, Dividend, MSD;
cout << "Input:";
cin >> Input;
Divisor = 1;
Dividend = Input;
if (Input < 0)
{
Dividend *= -1;
cout << "minus ";
}
cout << Dividend;
while (Dividend > 9)
{
Divisor = Divisor * 10;
Dividend = Dividend / 10;
}
while (Divisor != 0)
{
MSD = Input / Divisor;
switch (MSD)
{
case 0:
cout << "zero ";
break;
case 1:
cout << "one ";
break;
case 2:
cout << "two ";
break;
case 3:
cout << "three ";
break;
case 4:
cout << "four ";
break;
case 5:
cout << "five ";
break;
case 6:
cout << "six ";
break;
case 7:
cout << "seven ";
break;
case 8:
cout << "eight ";
break;
case 9:
cout << "nine ";
break;
}
Input = Input - (MSD * Divisor);
Divisor /= 10;
}
return 0;
}
答案 0 :(得分:5)
更改
if (Input < 0)
{
Dividend *= -1;
cout << "minus ";
}
到
if (Input < 0)
{
Input *= -1;
cout << "minus ";
}
但是真的,你调试了吗?:)
答案 1 :(得分:2)
我认为您的代码不适用于负数。看看这一行:
while (Divisor != 0) {
MSD = Input / Divisor;
// switch statement
}
如果用户输入Input
的负值,则不会在switch语句中遇到任何情况。我相信您要确保使用Input
的绝对值,而不是用户输入的值。
答案 2 :(得分:0)
作品!谢谢。
#include <iostream> // Necessary header
using namespace std;
const int DIV = 10; // Avoid Magic Numbers
const int REM = 9;
int main()
{
signed int Input, Divisor, Dividend, MSD; // Signed because negative values need to be read
cout << "Input:";
cin >> Input;
cout << "Output: ";
if (Input < 0) // If the input is negative, make it positive
{
Input = -Input;
cout << "minus ";
}
Divisor = 1; // Initialize Divisor to 1
Dividend = Input; // Dividend is equal to input number
while (Dividend > REM)
{
Divisor *= DIV;
Dividend /= DIV;
}
while (Divisor != 0) // While the Divisor is not 0
{
MSD = Input / Divisor; // The most significant digit is obtained
switch (MSD)
{
case 0: // Multiple cases to print all digits 0 to 9
cout << "zero ";
break;
case 1:
cout << "one ";
break;
case 2:
cout << "two ";
break;
case 3:
cout << "three ";
break;
case 4:
cout << "four ";
break;
case 5:
cout << "five ";
break;
case 6:
cout << "six ";
break;
case 7:
cout << "seven ";
break;
case 8:
cout << "eight ";
break;
case 9:
cout << "nine ";
break;
}
Input -= MSD * Divisor; // Change input so next digit can be obtained
Divisor /= DIV;
}
return 0;
} // End main method