n进制转为十进制

主程序代码 -

 1 #include <stdio.h>
 2 #include <string.h>
 3 main()
 4 {
 5     long t1;
 6     int i, n, t, t3;
 7     char a[100];
 8     printf("please input a number string:
");
 9     gets(a);                                            /*输入n进制数存到数组a中*/
10     strupr(a);                                            /*将a中的小写字母转换成大写字母*/
11     t3 = strlen(a);                                        /*求出数组a的长度*/
12     t1 = 0;                                                /*为t1赋初值0*/
13     printf("please input n(2or8or16):
");
14     scanf("%d", &n);                                        /*输入进制数*/
15     for (i = 0; i < t3; i++)
16     {
17         if (a[i] - '0' >= n && a[i] < 'A' || a[i] - 'A' + 10 >= n)            /*判断输入的数据和进制数是否相符*/
18         {
19             printf("data error!!");                            /*输出错误*/
20             exit(0);                                        /*退出程序*/
21         }
22         if (a[i] >= '0' && a[i] <= '9')                            /*判断是否为数字*/
23             t = a[i] - '0';                                    /*求出该数字赋给t*/
24         else if (n >= 11 && (a[i] >= 'A' && a[i] <= 'A' + n - 10))        /*判断是否为字母*/
25             t = a[i] - 'A' + 10;                                /*求出字母所代表的十进制数*/
26         t1 = t1 * n + t;                                    /*求出最终转换成的十进制数*/
27     }
28     printf("the decimal is %ld
", t1);                            /*将最终结果输出*/
29 } 

程序来自 :c语言程序开发范例宝典

原文地址:https://www.cnblogs.com/ottox/p/3719653.html