我想做的是,创建一个程序,将十进制值转换为其他数字系统(二进制、八进制和十六进制)并显示原始十进制值以及转换后的值。
它在第一次运行时运行良好,但是当外部 for 循环再次运行程序时,内部 for 循环打印的先前值也会在下一次运行的输出之后立即打印。有什么建议么?
尝试运行它,然后自己看看...源代码:-
#include <iostream>
using namespace std;
int main()
{
cout << "This program will help in Decimal to other radix conversion :-" << endl;
const int i = 10;
//Declaring array to store remainder values...
int RemArray [i] = {0};
//Declaring variable to use it as index of RemArray[]...
short int R=0;
char Exit = '\0';
//To iterate the whole program...
for (;;)
{
cout << "Enter Decimal digit: ";
long long int Decimal = 0;
cin >> Decimal;
long long int TempDecimal = Decimal;
cout << "Enter Desired Radix: ";
int Radix = 0;
cin >> Radix;
long long int Quotient = 1;
long long int Remainder = 0;
cout << endl;
while (Quotient != 0)
{
//Formula for conversion...
Quotient = Decimal / Radix;
Remainder = Decimal % Radix;
cout << "Quotient: " << Quotient << " <-> " << "Remainder: ";
//Using switch case so that hexa-decimal values could also be printed...
switch (Remainder)
{
case 10:
cout << "A" << endl;
break;
case 11:
cout << "B" << endl;
break;
case 12:
cout << "C" << endl;
break;
case 13:
cout << "D" << endl;
break;
case 14:
cout << "E" << endl;
break;
case 15:
cout << "F" << endl;
break;
default:
cout << Remainder << endl;
break;
}
Decimal = Quotient;
//Using array to store remainder values...to print them all together
RemArray [R] = Remainder;
R++;
}
cout << endl;
cout << "Therefore, " << TempDecimal << " = ";
/*Output the result...But When the program runs again, values obtained here remains
on the screen and prints them too on the next run of this loop...*/
for (int NewR = R-1, z=0; (NewR >= 0) && (z < R); NewR--,z++)
{
switch (RemArray [NewR])
{
case 10:
cout << "A";
break;
case 11:
cout << "B";
break;
case 12:
cout << "C";
break;
case 13:
cout << "D";
break;
case 14:
cout << "E";
break;
case 15:
cout << "F";
break;
default:
cout << RemArray [NewR];
break;
}
}
//Asking user to iterate the program again...
cout << endl << "Want to convert another digit (y/n): ";
cin >> Exit;
cout << endl;
if (Exit == 'n')
{
break;
}
}
cout << "GoodBye !!!" << endl;
return 0;
}