vendredi 3 juillet 2020

Unexpedted behavious while base conversion

I am new to C++, and try to convert base 10 to base 8 or base 16. and observe unexpected behavior.

1 #include <iostream>
2 #include <string>    
3
4 using std::cout;
5 using std::endl;
6 using std::cin;
7 using std::oct;
8 using std::hex;
9
10 int main ()
11 {
12        int number = 20 ;   // base 10
13                       
14        cout << "conversion of " << number <<" to octal " << oct << number << endl;
15        cout << "conversion of " << number <<" to hexadecimal " << hex << number << endl;
16
17        cout << "Enter your choice for conversion 1 - oct and 2- hex"<< endl;
18        int test;
19        cin >> test;
20        if (test == 1) {
21                cout << "you want to convert decimal into octal"<< endl;
22                int tech;
23                cout << "Enter the number you want to convert " << endl;
24                cin >> tech;
25                cout << tech << " Octal Conversion is = " << oct << tech << endl;
26        }
27        else if (test == 2) {
28                cout << "you want to convert decimal into hexadecimal"<< endl;
29                int tech;
30                cout << "Enter the number you want to convert " << endl;
31                cin >> tech;
32                cout << tech <<" Hex Conversion is = " << hex << tech << endl;
33        }
34        else {
35                cout << "you have entered wrong choice" << endl;
36        }
37
38 return 0;
39
40 }

After compilation and run with g++ literal_constant.cpp -std=c++11 -o literal_constant && ./literal_constant

Console Output is

conversion of 20 to octal 24
conversion of 24 to hexadecimal 14
Enter your choice for conversion 1 - oct and 2- hex
1
you want to convert decimal into octal
Enter the number you want to convert 
60
3c Octal Conversion is = 74

unaware of these lines console output,

1 - convertion of 24 to hexadecimal 14  // after first time converting the number from base 10 to base 7, and then again convert this to base 16 with same base 10 number, will take the previous converted number
2 - 3c Octal Conversion is = 74        // why base 10 entered number printed as base 16 which is 3c, this might be coming from line no 15 if i change hex to oct it will print base 8.

Aucun commentaire:

Enregistrer un commentaire