?? convert.cpp
字號:
///////////////////////////////////////////////////////////
// Module : convert.cpp
//
// Purpose : Converts numbers from decimal (base 10) to
// some number base (2-10).
///////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
///////////////////////////////////////////////////////////
// Function Declarations
string Convert(const int& num, const int& newbase);
string ReverseStr(const string& str);
///////////////////////////////////////////////////////////
// Convert()
string Convert(const int& num, const int& newbase)
{
string str;
char ch;
int remainder = 0;
int quotient = num;
while (quotient > 0)
{
remainder = quotient % newbase;
quotient = quotient / newbase;
// Convert remainder to a char and add it to string
itoa(remainder, &ch, 10);
str += ch;
};
// Because the bits in the number are converted from
// low to high, we must reverse it to get the proper
// order.
str = ReverseStr(str);
return str;
}
///////////////////////////////////////////////////////////
// ReverseStr()
string ReverseStr(const string& s1)
{
string str = s1;
// Use pointer arithmetic to reverse the string
int last = str.size(); // Number of chars in string
char *s = &str[0]; // Get pointer to start char
char *e = &str[last-1]; // Get pointer to end char
char temp;
do
{
// Swap outer digits
temp = *s; // temp = start
*s = *e; // start = end
*e = temp; // end = temp
// Move inward, into the string from both ends
++s;
--e;
}
while (s < e); // repeat until midpoint
return str;
}
///////////////////////////////////////////////////////////
// Driver
void main()
{
int num;
int base;
char quit;
do
{
do
{
cout << "In what base shall we work work "
<< "(2-10)? >";
cin >> base;
}
while ((base < 2) || (base > 10));
do
{
cout << "Enter a positive decimal integer "
<< "for conversion >";
cin >> num;
}
while (num < 0);
// Convert bases
string answer = Convert(num, base);
// Write output
cout << num << " = " << answer << " in base "
<< base << endl;
cout << endl;
// See if the user wants to continue or quit
cout << "Enter Q to quit, C to continue >";
cin >> quit;
cout << endl;
}
while ((quit != 'Q') && (quit != 'q'));
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -