【发布时间】:2017-02-09 17:28:34
【问题描述】:
我正在编写一个 C++ 代码,它将无符号的以 10 为基数的整数转换为 2 到 36 之间的任何其他基数。我有一段时间没有编写代码了,所以我正在重新学习所有内容。我的问题是:我怎样才能将它保留为 printf,最后没有 cout,并且仍然显示 ascii 值。是否有可能让它变得简单(基本)。对不起,如果我没有正确格式化。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int InitialNum, BaseNum, Num, x;
string FinalNum, Temp;
printf("Enter an unsigned integer of base ten: \n");//Prompt user for input
scanf_s("%d", &InitialNum);
printf("Enter the base you want to convert to (min2, max36): \n");
scanf_s("%d", &BaseNum);
x = InitialNum; //save the base 10 number to display at the end
while (InitialNum != 0) //continue dividing until original input is 0
{
Num = InitialNum % BaseNum; //save remainder to Num
int ascii = 48; //declare conversion variable (from int to char)
for (int i = 0; i < 32; ++i)//for loop converts Num from int 0-15 to char '0'-'9', 'A'-'F'
{
if(Num == i)
Temp = ascii;
ascii += 1;
if (ascii == 58)//skip from 9 to A on the ascii table and continue
ascii = 65;
}
FinalNum = Temp + FinalNum;//add to the final answer(additions to the left)
InitialNum /= BaseNum; //the initial base10 number gets divided by the base and saved as the quotient
}
printf("The number %d converted to base %d is:", x, BaseNum);
cout<<(FinalNum);
system("PAUSE");
return 0;
}
【问题讨论】:
-
参见web.archive.org/web/20150204050528/http://www.jb.man.ac.uk/… 了解
itoa(非标准通用函数)的内部结构。哦等等,移动版还在上线,strudel.org.uk/itoa -
你为什么要使用硬编码的 ascii 值,例如
48而不是'0'?你把它标记为 C++ 那么你为什么关心 printf 和 scanf 呢?学习使用 cin 和 cout。 -
我们的教授希望我们熟悉 printf 和 scanf。
-
我修复了 kfsone 提到的 ascii 问题。我仍然需要解决 cout 问题...
-
@noobisko
cout问题究竟是什么?你必须用printf()替换它?`