C++ While Loop: Hex & Oct, & Dec

C++ While Loop: Hex & Oct, & Dec

本文关键字:Oct Dec Hex While Loop C++      更新时间:2023-10-16

我目前正在编写一个代码:

取2个十进制数,然后在紧凑的查看表中以八进制、十六进制以及原始格式显示。

目前,我被限制为while循环。代码看起来像:

cout << "Enter in two hexadecimal numbers that will be the beginning and endn";
while (num1 <= num2){
    // takes 2 hexadecimal inputs
    cin >> hex >> num1; cin >> hex >> num2; 
    cout << "DecimaltOctaltHexadecimaln";
    cout << "***********************************n";

虽然不多,但这已经折磨了我一段时间了。我目前不知道如何处理这个问题。

注意:我不知道该增加什么,也不知道是否需要另一个变量。如果你能给我建议,或者给我指明正确的方向,那就太好了。

首先,您需要获取值,然后使用以下内容从num1循环到num2

cout << "Enter in two hexadecimal numbers that will be the beginning and endn";
cin >> hex >> num1; cin >> hex >> num2; //takes 2 hexadecimal inputs
while (num1 <= num2) {
    // ... do stuff
    ++num1;
}

然后,您可能只需要io操纵器作为输入,以在循环的"做事"部分的不同基础上输出num1

有一件事-您可能想在读取值后开始循环

cout << "Enter in two hexadecimal numbers that will be the beginning and end" << endl;
cin >> hex >> num1; cin >> hex >> num2; //takes 2 hexadecimal inputs
while (num1<=num2)
{
   cout << num1 << "  " << oct <<  num1 << "  " << hex << num1 <<endl;
   num1++;
}

我可能会做这样的事情。。。

#include <iomanip>
.........
int num1 = 0;
int num2 = 0;
cout << "Enter number 1: ";
cin >> num1;
cout << "Enter number 2: ";
cin >> num2;
if(num1 > num2){
    cout << "number 1 needs to be smaller than number 2; exiting...";
    return 0;
}
cout << "DecimaltOctaltHexadecimaln";
cout << "***********************************n";
while(num1 <= num2){
    cout << dec << num1 << " " << oct << num1 << " " << hex << num1 << endl;
    num1++;
}

查看c++的ios标志