我是C ++编程的新手。我正在编写一个读取两个整数的程序,其中一个是十进制数N
,另一个是我想要转换为的基本系统b
。对于基数16,A
表示10,B
表示11,依此类推。
#include<iostream>
using namespace std;
string dec2b();
int N, b;
int rem =0;
int main(){
cout<<"please input a decimal positive number: "; cin>>N;
cout<<"please input the desired base: "; cin>>b;
string s = dec2b();
cout<<'"'<<N<<'"'<<" in base-10 system = \""<<s<<"\" in base-"<<b<<"system"<<endl;
return 0;
}
string dec2b()
{
string s = "";
while(N>0)
{
if (b==16)
{
rem = N%b;
if (rem>9)
{
switch (rem)
{
case 10: s= "A" + s; break;
case 11: s= "B" + s; break;
case 12: s= "C" + s; break;
case 13: s= "D" + s; break;
case 14: s= "E" + s; break;
case 15: s= "F" + s; break;
}
}
else
{
s = char(rem+48) +s;
}
}
else
{
rem = N%b;
s = char(rem+48) +s;
}
N = N/b;
}
if (s=="")
{cout<<"0";}
else
{cout<<s; }
return s;
}
答案 0 :(得分:0)
在N
函数中设置b
和main()
本地,并将函数string dec2b()
更改为string dec2b(int N, int b)
。同时将int rem = 0
移至dec2b
函数。避免使用全局变量。
string dec2b(int N, int b);
int main()
{
int N, b; // <- add here
cout << "please input a decimal positive number: "; cin >> N;
cout << "please input the desired base: "; cin >> b;
string s = dec2b(N, b); // <- change here
cout << '"' << N << '"' << " in base-10 system = \"" << s.c_str() << "\" in base-" << b << " system" << endl;
return 0;
}
string dec2b(int N, int b)
{
int rem = 0;
// ...
// your code here
}
N = 14和b = 16的结果将是: 的&#34; 14&#34;在base-10系统中=&#34; E&#34;在base-16系统中
答案 1 :(得分:0)
要转换的数字作为字符串传递给函数,并且base是要转换数字的基础。
C ++程序,可以将小数转换为任何给定的底数
#include<bits/stdc++.h>
using namespace std;
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10. 'B'
// for 11
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}
// Utility function to reverse a string
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
// Function to convert a given decimal number
// to a base 'base' and
char* fromDeci(char res[], int base, int inputNum)
{
int index = 0; // Initialize index of result
// Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (inputNum > 0)
{
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';
// Reverse the result
strev(res);
return res;
}
int main()
{
int inputNum = 282, base = 16;
char res[100];
printf("Equivalent of %d in base %d is "
" %s\n", inputNum, base, fromDeci(res, base, inputNum));
return 0;
}
输出:以16为基数的282的等效值为11A