서명되지 않은 int 배열에서 소수점으로 스캔 한 (ScanF)을 소수점으로 변환

StackOverflow https://stackoverflow.com/questions/9033840

  •  14-11-2019
  •  | 
  •  

문제

여기에 4 자리 헥사를 DEC로 변환하려고하지만 성공하지 못했습니다. 여기에 내 코드가 있습니다.

unsigned int array[4];                         

printf("Type in 4-digit hexa: \n");

scanf("%x", &array);

while(getchar() != '\n');

printf("Your number in dec is %u \n", array);
.

나는 그것에 무엇이 잘못되었는지 모르지만 정확한 DEC 출력을 포기하지 않을 것입니다. EEFF를 넣을 때 61183을주고 있지만 프로그램은 65518 인쇄에 보관되어 있습니다.

이 번호는 어디에서 왔습니까? 내 코드가 무엇이 잘못 되었습니까? FFFF가 65385와 같고 서명되지 않은 INT의 범위는 0 ~ 65535라는 사실에 따라 부호없는 INT를 사용했습니다. 데이터 범위에 문제가 없어야합니다.

일부 검색을 수행 한 후에 지금 내가 생각할 수있는 유일한 것은이 문제가 부호없는 INT의 크기 또는 sth의 크기와 함께 할 수 있다는 것입니다. 나는 설명을 읽었지 만 이해하지 못했습니다.

알고 있습니다. 이것은 중복 일 수 있지만 나는 더 쉬운 설명을 요구합니다. 왜 이것이 작동하지 않는지. 솔직히 말해서, 나는이 사이트와 프로그래밍 모두에 대해 절대적으로 Newby이므로 코딩으로 나에게 쉽게 가십시오. Fyi, 나는 stdio.h의 밖에서 아무것도 모른다.

도움이 되었습니까?

해결책

You are passing a pointer, array, to printf(). There is no need for an array here, what you're trying to scan and print is a single number.

unsigned int number;

printf("Type in 4-digit hex:\n");

if (scanf("%x", &number) == 1)
  printf("Your number in dec is %u \n", number);

Also note that it's considered a good idea to check if scanf() succeeds or not, by inspecting the return value.

다른 팁

You don't need an array for that:

unsigned int val;
printf("Type in 4-digit hexa: \n");
scanf("%x", &val);
printf("Your number in dec is %u \n", val);

a. print array[0], not array.

(optional) b. scan to array, not to &array.

c. what is the point of the getchar()?

No, you must input as string to a point of characters. After that, you convert to number. Ex

char *str=char[10];
int i=0,num=0;
printf("Type in 4-digit hexa: ");
scanf("%s",str);

for(i=0;str[i]!='\0';i++)
   if(str[i]>='0' && str[i]<='9') num=16*num+str[i]-'0';
   else if(str[i]>='a' && str[i]<='f') num=16*num+str[i]-'a';
   else if(str[i]>='A' && str[i]<='F') num=16*num+str[i]-'A';

printf("Dec is %d",num);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top