0
我目前正在研究將十進制輸入轉換爲十六進制等效的程序。我計劃使用矢量來系統地收集這些值,然後將它們反向吐出(因此以十六進制表示)。但是我遇到了很多問題。所有的投入都會按照預期工作,然後事情會變得很奇怪。輸入16將導致系統輸出一個笑臉,在2個不同的彩色笑臉中輸入18個結果,23個導致系統發出嘟嘟聲。十進制到十六進制程序代理
這應該是一個相對直接的代碼,它只是以我從未見過的方式行事!希望這個信息可以幫助
編輯:我知道std :: hex函數,雖然這是一個類,我們不允許使用它unfortunatley。
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main(){
int input, tester = 0, switchStuff, county = 0, remainderCount = 1, inputCount, remainder = 1, remainderCount2, inputCount2;
string stopGo;
char remainderLetter;
do{
while (tester != 1){
cout << "Enter the number you would like to convert to Hex format: ";
cin >> input;
if (cin.fail()){ //check if user input is valid
cout << "Error: that is not a valid integer.\n";
cin.clear(); cin.ignore(INT_MAX, '\n'); //Clear input buffer
continue; //continue skips to top of loop if user input is invalid, allowing another attempt
}
else{
tester = 1; //Tester variable allows loop to end when good value input
}
}
inputCount = input;
while(inputCount != 0){
remainderCount = inputCount % 16;
inputCount = (inputCount - remainderCount)/16;
county++;
}
vector<string>userInfo(county);
inputCount2 = input;
for (int i = 0; county > i; i++){
remainderCount2 = inputCount2 % 16;
inputCount2 = (inputCount2 - remainderCount2)/16;
if (remainderCount2 == 10){
remainderLetter = 'A';
}
else if (remainderCount2 == 11){
remainderLetter = 'B';
}
if (remainderCount2 == 12){
remainderLetter = 'C';
}
else if (remainderCount2 == 13){
remainderLetter = 'D';
}
if (remainderCount2 == 14){
remainderLetter = 'E';
}
else if (remainderCount2 == 15){
remainderLetter = 'F';
}
if (remainderCount2 >= 10){
userInfo[i] = remainderLetter;
}
else{
userInfo[i] = remainderCount2;
}
}
cout << "The result in Hexadecimal format is: ";
for (int i = 0; i < county; i++)
cout << userInfo[i];
cout << endl << "Would you like to continue? (Enter Yes/No): "; //Check whether to continue or not
cin >> stopGo;
cout << endl;
tester = 0;
}while ((stopGo.compare("Yes") == 0) || (stopGo.compare("yes") == 0) || (stopGo.compare("y") == 0) || (stopGo.compare("Y") == 0)); //Leaves user with a range of ways to say 'yes'
cout << "Thank you for using this program!" << endl;
system("pause");
}
您是否知道,您可以使用std :: hex在std :: out上以十六進制格式打印任何整數數字? – MikeMB 2014-12-04 08:01:03
也許你會考慮切換到這樣的: cout << hex << numberToConvert; numberToConvert - 你想要轉換爲十進制格式的數字 它會做同樣的事情,你只需要改變輸出數據格式。 – MateuszZawadzki 2014-12-04 08:01:56
沒有時間給出完整的答案,但代碼的最後一部分很糟糕:考慮到'A'的ASCII代碼是65,你可以使用類似'remainingLetter = remainderCount2 + 55;'或者更好的'remainingLetter = remainderCount2 +'A'-10;' – kebs 2014-12-04 08:17:52