【发布时间】:2017-03-21 13:25:43
【问题描述】:
提前感谢您的帮助。
我被分配了一个包含以下输入的作业:
init_base which is the base we are converting to. 2<=init_base and 36>= init_base
in_num which is the decimal number that is to be converted
in_num gets written to multiple times for each decimal number
the input is terminated with a -1
我被告知在数字大于 9 时使用大写字母。
我已经为解决方案编写了代码。代码运行,但我不断得到一个奇怪的输出。我不确定这是为什么。我认为这与我的数据类型转换有关。但是我不太确定出了什么问题。
#include <iostream>
#include <cmath>
#include <string>
#include <stdlib.h>
#include <algorithm>
using namespace std;
string ans;
int counter = 0;
bool Alpha_check(int val){
if(val>9){
return true;
}
else{
return false;
}
}
char Al_conv(int val){
if(Alpha_check(val)){
return char(val+55);
}
else {
return char((val-48)+'0');
}
}
void add_On(int c){
ans.append(Al_conv(c));
counter++;
}
int div_loop(int num, int base){
int temp = int(num/base);
int temp2 = int(num%base);
add_On(temp2);
return temp;
}
void add_line(int number){
ans[number] = '\n';
}
int main(){
int init_base, in_num = 0;
cin >> init_base;
cin >> in_num;
do{
string rem;
int init_count = counter;
while(in_num!=0){
in_num = div_loop(in_num,init_base);
}
int helper = int(floor((counter-init_count)/2));
for(int y = 0; y < helper; y++){
int temp = ans[y+init_count];
ans[y+init_count] = ans[(counter-1)-y];
ans[(counter-1)-y] = temp;
}
add_line(counter);
counter++;
cin >> in_num;
}while(in_num!=-1);
ans[counter] = '\0';
for(int gh = 0; gh < ans.length(); gh++){
cout << ans[gh];
}
cout << endl;
return 0;
}
这里还有一个链接供您关注http://ideone.com/qFOtyl 以查看输出。
【问题讨论】:
-
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs
-
谢谢@NathanOliver。我一般不使用调试器。我使用带有变量详细信息等的输出语句。但是您知道针对 Windows 10 的 c++ 有什么好的调试器吗?我目前一直在 Ubuntu 上使用 CLI,但我还没有开始在我的笔记本电脑上划分我的驱动器。
-
我真的很喜欢 MSVS 的调试器。它对 C++ 的支持不是最好的,但 2015 和 2017 版的表现相当不错。
-
@NathanOliver 好的,谢谢。会试一试。谢谢
标签: c++ string type-conversion