将数字转换为C ++中的负基表示
在本教程中,我们将讨论将数字转换为负数基数表示形式的程序。
为此,我们将提供一个数字和相应的负数基数。我们的任务是将给定的数字转换为其负的基数。对于负基本值,我们仅允许使用介于-2和-10之间的值。
示例
#include <bits/stdc++.h>
using namespace std;
//将整数转换为字符串
string convert_str(int n){
string str;
stringstream ss;
ss << n;
ss >> str;
return str;
}
//将n转换为负基
string convert_nb(int n, int negBase){
//零的负基当量为零
if (n == 0)
return "0";
string converted = "";
while (n != 0){
//从负数中减去余数
int remainder = n % negBase;
n /= negBase;
//将余数更改为其绝对值
if (remainder < 0) {
remainder += (-negBase);
n += 1;
}
//将余数转换为字符串,将其添加到结果中
converted = convert_str(remainder) + converted;
}
return converted;
}
int main() {
int n = 9;
int negBase = -3;
cout << convert_nb(n, negBase);
return 0;
}输出结果
100
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志