該代碼應該將二進制數轉換爲十進制數,但它不。任何人都可以請檢查我可能出錯的地方。從二進制轉換爲十進制
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char s[40];
int base;
int index,n,p,sum=0; /* n is the number of digits in the converted value */
printf("enter the number and base: ");
scanf("%s %d",s,&base);
for(n=strlen(s)-1;n>=0;n--)
{
p=strlen(s);
for(index=strlen(s)-(p-1); index<=p; index++)
{
sum += s[index] * pow(base,n);
}
}
printf("decimal no. is %d",sum);
printf("\n");
}
輸出::
enter the number and base:1011
2
十進制沒有。是1487
你似乎很喜歡的strlen()了很多。 – wildplasser 2013-03-28 00:32:55
你也喜歡循環。你可以用一個循環做到這一點,你甚至不需要math.h.建議:嘗試用自然語言向自己描述如何去做這件事。一步一步仔細思考,然後將其轉爲代碼。 – 2013-03-28 00:33:39
'p = strlen(s);'是不變的,你永遠不會改變's' – corny 2013-03-28 00:35:37