I have been learning c language for about a month.
Just like the title says.
The last for statement seems to be wrong, but it doesn't make sense.
I know that the cord is dirty and there is an easier way.
However, I'm in trouble because they told me to do it without using it.
Please tell me the algorithm of the for statement below without changing the for statement above.
#include<stdio.h>
int main() {
charc;
inti,a[1000];
printf("Input hexadecimal number:");
for(i=0;;i++){
scanf("%c", & c);
if(c=='\n'){
i - = 1;
break;
} else if(c=='0') {
a[i] = 0;
} else if(c=='1') {
a[i] = 1;
} else if(c=='2') {
a[i] = 2;
} else if(c=='3') {
a[i] = 3;
} else if(c=='4') {
a[i] = 4;
} else if(c=='5') {
a[i] = 5;
} else if(c=='6') {
a[i] = 6;
} else if(c=='7') {
a[i] = 7;
} else if(c=='8') {
a[i] = 8;
} else if(c=='9') {
a[i] = 9;
} else if(c=='a') {
a[i] = 10;
} else if(c=='b') {
a[i] = 11;
} else if(c=='c') {
a[i] = 12;
} else if(c=='d') {
a[i] = 13;
} else if(c=='e') {
a[i] = 14;
} else if(c=='f') {
a[i] = 15;
}
}
intk = 0, x, y, z = 1;
for(x=0;x<i+1;x++){
for(y=0;y<i-x;y++){
z*=16;
}
k + = a[x]*z;
printf("%d\n%d\n",k,z);
}
printf("Decimal number is %d\n",k);
return 0;
}
This is probably what I want to do.
Input hexadecimal number:12
a[0]=1 a[1]=2
and
k=a[0]*16^1+a[1]*16^0
Calculate .
It's okay to quantify the characters and store them in an array, but the loop to find the sum is a little different.
If you set the above formula to three digits, the difference will be clear.
Input hexadecimal number:123
a[0] = 1 a[1] = 2 a[2] = 3
k=a[0]*16^2+a[1]*16^1+a[2]*16^0
Rewrite using the first code as much as possible
intk = 0, x, y, z;
for(x=0;x<i+1;x++){
z = 1;
for(y=i-x;y>0;y--){
z*=16;
}
k + = a[x]*z;
printf("%d\n%d\n",k,z);
}
printf("Decimal number is %d\n",k);
I think I can do it now.
© 2024 OneMinuteCode. All rights reserved.