三进制转换十进制C语言的程序
时间: 2024-09-21 19:07:14 浏览: 76
welcomewindow,二进制转10进制c语言源码,c语言程序
在C语言中,将三进制数转换成十进制数通常可以利用循环和乘法运算来实现。下面是一个简单的示例程序,它接受用户输入的三进制字符串并计算其对应的十进制值:
```c
#include <stdio.h>
#include <string.h>
// Function to convert a binary number represented as string to decimal
int ternaryToDecimal(char *ternaryNum) {
int len = strlen(ternaryNum);
int decimalValue = 0;
int base = 1; // Since we are starting from rightmost digit
for (int i = len - 1; i >= 0; i--) {
if (ternaryNum[i] == '1') {
decimalValue += base;
} else if (ternaryNum[i] == '2') {
decimalValue += 2 * base;
} else if (ternaryNum[i] == '0') {
// Do nothing, it's the place holder in ternary system
} else {
printf("Invalid input! Only '0', '1', and '2' allowed in ternary.\n");
return -1;
}
base *= 3;
}
return decimalValue;
}
int main() {
char ternary[100];
printf("Enter a three-digit number in ternary format: ");
fgets(ternary, sizeof(ternary), stdin);
// Remove newline character at the end of input
ternary[strcspn(ternary, "\n")] = '\0';
int decimalResult = ternaryToDecimal(ternary);
if (decimalResult != -1) {
printf("The decimal equivalent is: %d\n", decimalResult);
}
return 0;
}
```
阅读全文