c语言,定义一个函数,返回其整数变元的字符串表示,例如如果这个变元是-225,函数就返回“-225”,有图

#include<stdio.h>
#include<stdlib.h>
char* shu(long a,char*q)
{
int n=1;
int i=0;
long b=a;
if(a<0)
b=-a;
while(n)
{
*(q+i++)=b%10;
n=b/10;
}
if(a<0)
*(q+i++)='-';
char temp='0';
for(int j=0;j<i/2;j++)
{
temp=*(q+j);
*(q+j)=*(q+i-1-j);
*(q+i-1-j)=*(q+j);
}
return q;
}
int main(void)
{
int calpacility=15;
char*p=(char*)calloc(calpacility,sizeof(char));
long m=0l;
scanf("%ld",&m);
printf("\n%ld is %s",m,shu(m,p));

}
为什么程序会运行错误,图:

#include <stdio.h>
#include <stdlib.h>

char *shu(long a,char *q) {
int i = 0,j,temp;
long b = a;
if(a < 0) a = -a;
while(a) {
*(q + i++) = a % 10 + '0';
a /= 10;
}
if(b < 0) q[i++] = '-';
q[i] = '\0';
    for(j = 0;j < i/2; j++) {
temp = q[j];
q[j] = q[i - 1 - j];
q[i - 1 - j] = temp;
    }
    return q;
}

int main(void) {
int calpacility = 15;
char *p = (char *)calloc(calpacility,sizeof(char));
long m = 0l;
scanf("%ld",&m);
    printf("%ld is \"%s\"\n",m,shu(m,p));
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-19
运行错误的原因在于给char变量赋值一个整数如1,结果可不是字符'1'而是asc码1
所以给应该写成:
c=i+'0';
另外你的程序里逻辑错误也比较多,打印结果只能是几个个位数字的重复,你自己先检查一下吧追问

谢谢你。。。哎,电脑面前做久了总是这样。。。。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网