#include <stdio.h>
int main(void) {
int x,y,z=0,number,digit;
char c;
int sum = 0;
int temp = 0;
while (z==0){
printf("enter 2-9 for hex\n");
scanf("%c",&c);
x = (int)c-48;
if((int)c>49 && (int)c<59){
printf("enter number");
scanf("%d",&number);
break;
}
else if ((int)c<50 || (int)c>58){
printf("wrong number\n");
z==0;
}
else
printf("error");
z==0;
}
while (number != 0) {
digit = number % 10;
number = number / 10;
if (digit >= x) {
printf("wrong input!!!");
return 0;
}
else {
int temp1 = temp;
if (temp1 == 0) {
digit = digit * 1;
}
else {
while (temp1 != 0) {
digit = digit * x;
temp1--;
}
}
}
sum = sum + digit;
temp = temp + 1;
}
printf("\nThe number in Decimal is:%d", sum);
}
이것은 내 코드로, 16 진수를 십진수로 변환하는 것에 관한 것입니다. 질문은 내가 2-9를 입력하면 모든 것이 좋지만 1을 입력하면 첫 번째 while 루프는 2 번, 10-99를 입력하면 3 번 반복됩니다. 100-999를 입력하면 4 번 반복됩니다.
Z == 0으로 설정 한 후에도 여전히 여러 번 실행되는 이유는 무엇입니까?
상황은 z의 조건이 항상 사실입니다. 시작 조건 iz == 0, 이것은 while 루프를 시작합니다. while 루프는 z가 0이 아닐 때 멈 춥니 다. 따라서 while 루프의 어딘가에서 z를 0이 아니도록 변경해야합니다. 그런 다음 while 루프가 중지됩니다. 그리고 if-else에는 닫고 여는 "{}"를 사용하십시오. 이는 가독성을 높이고 도움을줍니다.
예를 들면 :
#include <stdio.h>
int main(void) {
int x,y,z=0,number,digit;
char c;
int sum = 0;
int temp = 0;
while (z==0){
printf("enter 2-9 for hex\n");
scanf("%c",&c);
x = (int)c-48;
if((int)c>49 && (int)c<59){
printf("enter number");
scanf("%d",&number);
break;
}
else if ((int)c<50 || (int)c>58){
printf("wrong number\n");
z==0;
}
else {
printf("error");
z==0;
}
z = 1;
}
while (number != 0) {
digit = number % 10;
number = number / 10;
if (digit >= x) {
printf("wrong input!!!");
return 0;
}
else {
int temp1 = temp;
if (temp1 == 0) {
digit = digit * 1;
}
else {
while (temp1 != 0) {
digit = digit * x;
temp1--;
}
}
}
sum = sum + digit;
temp = temp + 1;
}
printf("\nThe number in Decimal is:%d", sum);
}
도움이 되었기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다