[英]A c program to convert from octal to decimal
我試圖弄清楚我的代碼有什么問題,因為它總是只跳到printf("not an octal number part");
並且只輸出雖然在它之前有許多其他計算,但我正在嘗試調試它但似乎無法找到錯誤。 這是下面問題的夏天,我們還不允許使用指針。
AC程序以一行字符的形式輸入一個八進制數,並將輸入的字符存儲在一個數組中。 將八進制數轉換為十進制整數並使用 printf 在標准輸出上顯示十進制整數。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
int main() {
char my_strg[MAX_SIZE];
int c;
int res = 0;
int i = 0;
while ( (c = getchar()) != '\n') {
my_strg[i] = c;
i++;
}
int k = 0;
for(k = strlen(my_strg)-1; k >= 0; k--) {
if((my_strg[k] >= '0') && (my_strg[k] <= '7')) {
res += (pow(8, k) * (my_strg[k]-'0'));
} else if(my_strg[k] == '-') {
res *= -1;
} else {
printf("not an octal number");
break;
}
k++;
}
printf("%d\n", res);
}
您還沒有以空值結尾的my_strg
。 這意味着數組的開頭包含輸入,但其余部分包含亂碼。 進行邊界檢查也可能是一個好主意,這樣您就不會出現緩沖區溢出。
while (((c = getchar()) != '\n') && (i < MAX_SIZE-1)) {
my_strg[i] = c;
my_strg[i+1] = '\0';
i++;
}
非常簡單的功能。 需要更多的錯誤檢查。 注意'a' != 'A'
。 基數可以與數字表中的字符數一樣大
static const char digits[] = "0123456789abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRTSTUWXYZ";
long long ALMOST_anybase(const char *str, int base, int *errCode)
{
long long result = 0;
int sign = 1;
if(errCode) *errCode = 0;
if(str)
{
if(*str == '-') {sign = -1; str++;}
while(*str)
{
if(*str == '-')
{
if(errCode) *errCode = 3;
break;
}
else
{
char *ch;
if((ch = strchr(digits, *str)))
{
if(ch - digits >= base)
{
if(errCode) *errCode = 2;
break;
}
result *= base;
result += (ch - digits);
}
else
{
if(errCode) *errCode = 1;
break;
}
}
str++;
}
}
return result * sign;
}
int main(void)
{
int errCode;
long long result;
result = ALMOST_anybase("-4-4", 10, &errCode);
if(errCode)
{
printf("Wrong input string ErrCode = %d\n", errCode);
}
else
{
printf("result = %lld\n", result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.