练习:写一个函数,把两个正整数数相加后,返回结果,这个结果每三位加一个逗号,为了简单起见,这些数范围为(0,1000000).
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int topofstack;
int* Array;
int capacity;
};
typedef struct stack* Stack;
//push
void Push(Stack s,int X)
{
if(s->topofstack==s->capacity)
printf("the stack is full\n");
else
{
s->Array[s->topofstack+1]=X;
s->topofstack++;
}
}
//Pop
void Pop(Stack s)
{
if(s->topofstack==-1)
printf("error ,the stack is empty\n");
else
s->topofstack=s->topofstack-1;
}
//top
int top(Stack s)
{
if(s->topofstack!=-1)
return s->Array[s->topofstack];
else
printf("error ,the stack is empty\n");
}
Stack create(int Cap)
{
Stack s=malloc(sizeof(struct stack));
s->topofstack=-1;
s->Array=malloc(sizeof(int)*Cap);
s->capacity=Cap;
}
void Sum(int X,int Y)
{
int Z=X+Y;
Stack s=create(100);
int tem=Z;
while(tem!=0)
{
int tem2=tem;
if(tem2>1000)
{
Push(s,tem%1000);
tem=tem/1000;
}
else
{
printf("%d",tem);
while(s->topofstack!=-1)
{
if(top(s)<10)
{
printf(",00%d",top(s));
}
if(top(s)>=10&&top(s)<=99)
{
printf(",0%d",top(s));
}
if(top(s)>99&&top(s)<=999)
{
printf(",%d",top(s));
}
Pop(s);
}
tem=tem/1000;
}
}
}
主函数为
int main()
{
Sum(1000000,355550);
return 0;
}
当然也可以是这两个数是整数,返回值可以使负数,这样只需对上述代码进行一点改动便可。