回复 2楼 吹水佬
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
/*
void ReadBigInt(struct bigInt *x, const char *s);
void PrintBigInt(const struct bigInt *x);
void ChaNumber(struct bigInt a,int radix);
void CopyBigInt(struct bigInt *p, const struct bigInt *t);
int IsZero(const struct bigInt *x);
*/
struct bigInt {
int array[MAX]; /*数值*/
int sign; /*数值符号位*/
int length; /*数值位数*/
};
void ReadBigInt(struct bigInt *x, const char *s)
{
int i,j;
/* 输入数据必须有正负号 */
if(s[0] != '-' && s[0] != '+') {
printf("Input error!\n");
exit(1);
}
/* 读取符号位 */
if(s[0] == '-')
{
x->sign = 1;
}
if(s[0] == '+')
{
x->sign = 0;
}
/*读取数值位,低位数放在数组低下标处 */
for(i = strlen(s) - 1, j = 0; i > 0; i--, j++) {
if(isdigit(s[i])) {
x->array[j] = s[i] - '0';
} else {
exit(1);
}
}
/* 初始化数值位数 */
x->length = strlen(s) - 1;
}
void PrintBigInt(const struct bigInt *x)
{
int i;
/* 输出符号位 */
if(x->sign == 0)
{
printf("%c",'+');
}
if(x->sign == 1)
{
printf("%c",'-');
}
/* 输出数值位,从高位到低位显示 */
for(i = x->length - 1; i >= 0; i--) {
printf("%d", x->array[i]);
}
printf("\n");
}
void CopyBigInt(struct bigInt *p, const struct bigInt *t)
{
int i;
for(i = 0; i < t->length; i++) {
p->array[i] = t ->array[i];
}
p->length = t->length;
p->sign = t->sign;
}
int IsZero(const struct bigInt *x)
{
if(x->length == 1 && x->array[0] == 0) {
return 1;
} else {
return 0;
}
}
void ChaNumber(int radix,struct bigInt *a,struct bigInt *q)
{
int i,j;
struct bigInt temp,rt;
if(IsZero(a))
{
printf("wrong!");
return;
}
else {
for(i = a->length - 1 , j=0 ; i >= 0 ; i--,j++)
{
if(q->array[i] >= 2)
{
rt.array[j] = temp.array[i] % radix;
temp.array[i] = temp.array[i] / radix;
}
else {
temp.array[i] = temp.array[i] + 10;
rt.array[j] = temp.array[i] % radix;
temp.array[i] = temp.array[i] / radix;
temp.array[i-1] = temp.array[i-1] - 1;
}
}
/* 确定运算结果的符号位 */
rt.sign = a->sign;
/* 复制商和余数 */
CopyBigInt(q,&rt);
}
}
int main()
{
struct bigInt a,q; /*a为十进制数,q为商,t为余数*/
int k = 2;
char str[MAX];
printf("please input number:");
scanf("%s",str);
ReadBigInt(&a,str);
printf("十进制数");
PrintBigInt(&a);
ChaNumber(k,&a,&q);
printf("=二进制数");
PrintBigInt(&a);
}
+10是向前一位借1