부호없는 기본 10 정수를 2에서 36 사이의 다른 기준으로 변환하는 C++ 코드를 작성합니다. 코드를 작성하지 않아서 모든 것을 다시 배우는 것. 내 질문은 : 어떻게 그것을 마지막에 cout없이 printf로 유지하고 여전히 ascii 값을 표시 할 수 있습니다. 그리고 그것을 간단하게 (기본) 만들 수 있습니다. 내가 제대로 포맷하지 않으면 죄송합니다. 출력하기 위해밑 10에서 2와 36 사이의 임의의 밑수로 변환
#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;
}
itoa의 내장에 대한 좋은 설명은 http://web.archive.org/web/20150204050528/http://www.jb.man.ac.uk/~slowe/cpp/itoa.html을 참조하십시오. '(비표준 공통 함수). 오, 잠깐, 이동 된 버전은 여전히 온라인 상태입니다. http://www.strudel.org.uk/itoa/ –
왜 '0'을 쓰는 대신 '48'과 같은 하드 코딩 된 ASCII 값을 사용하고 있습니까? 이것을 C++로 태그 지정하면 printf와 scanf에 대해 왜 걱정하고 있습니까? cin과 cout을 사용하는 방법을 배우십시오. – kfsone
교수님은 printf와 scanf에 익숙해지기를 바랍니다. – noobisko