永发信息网

c++实现数字的补0成定长

答案:2  悬赏:80  手机版
解决时间 2021-11-07 09:16
c++实现数字的补0成定长
最佳答案
偷懒的方法,先转成数字,再格式化字串,不知道可不可以:
#include "stdlib.h"
#include "stdio.h"
#include "memory.h"
#include "string.h"

void convert( char* target , char* source , int n )
{

float a ;
char fstr[20] ;

a = (float)atof( source ) ;

sprintf( fstr, "%%0%d.2f" , n ) ;
sprintf( target , fstr , a ) ;
}

main()
{
char target[100] ;
char source[] = "-105.2" ;
convert( target , source , 9 ) ;
}
全部回答

思路大概是这样子:

void montageString(char *target, char *source, size_t targetLen){

if (strlen(source) == targetLen) return;

int i = 0,j=0,_dotN = 0;

for (i = strlen(source); i-- >0;){
if (*(source + i) == '.') break;
_dotN++;
}

if (_dotN < 2 && i >= 0){

if (target==NULL) target = (char *)malloc(targetLen + 1);

strcpy(target, source);
strcat(target, "0");
  
if (strlen(target) < targetLen){
if (*(target + 0) != '-') {
char *temp = (char*)malloc(targetLen+2);
 *(temp + 0) = '';

int k = strlen(target);
int _size1 = strlen(temp);
while (k {
strcat(temp, "0");
strcat(temp, target);
target =(char*)malloc(strlen(temp)+1);
_size1 = strlen(target);
*(target + 0) = '';
strcat(target, temp);
*(temp + 0) = '';
k++;
}

free(temp);
}
else{

char *temp = (char*)malloc(targetLen + 2);
for (j = 0; j < targetLen + 2;j++) *(temp + j) = '';

for (j = 1; j < strlen(target);j++)
{
*(temp + (j - 1)) = *(target + j);
}

//  
char *temp2 = (char*)malloc(strlen(temp) + 2);
*(temp2 + 0) = '';

int k = strlen(target);

while (k <=targetLen-1)
{
strcat(temp2, "0");
strcat(temp2, temp);
target = (char*)malloc(strlen(temp2) + 1);
*(target + 0) = '';
strcat(target, temp2);
*(temp2 + 0) = '';
k++;
}

temp2 = (char*)malloc(strlen(target) + 2);
for (j = 0; j < strlen(target) + 2; j++) *(temp2 + j) = '';
strcat(temp2, "-");
strcat(temp2, target);
target = (char*)malloc(strlen(temp2) + 1);
*(target + 0) = '';
strcat(target, temp2);

free(temp);
free(temp2);
}

}

}

printf(" target=%s ", target);

}追问高手啊!! 我写循环到一半写不下去了,看了第一个回答的运行了下也可以
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
一( )的稻子
初三历史 宣告美利坚合众国诞生的文件是什么?
为什么同样的服装款式会不不同的品牌?
8.09立方分米=()升()毫升
针织衣服变长了怎么办
RT54-160M2-6-1B电阻器怎么接线图
温州望江路婚纱礼服哪家好
北大的EMBA 研修结业证书 能查的到吗
手机的应用数据怎么恢复?
世界上数量最少的珍稀鸟类是(  )A.朱鹮B
恒通水暖电料五金地址在什么地方,我要处理点
当不断重复的日常让你感到疲惫时 是什么歌
请教各位散装攸县香干的冷藏保鲜方法?
唇线分明的男人是什么面相
求12riven跳跃的时空的启动码 本机硬体码:56
推荐资讯
求csol录过视频,而且在腾讯微博上成功发过的
冷库里的梨为什么拿出来会慢慢发黑点
o.39x3.5例竖式
课前预习有什么好处与不好
唉,前两次把女生约出来了,第三次不肯出来咋
国产发动机仓布置怎么那么空旷比如BYD速锐、
新买的多肉蓝鸟种了四五天了还是软软的,底部
梅陇七村怎么样?好不好?值不值得买?
亮仔眼镜地址在什么地方,我要处理点事!
《国境以南太阳以西_文学》最新txt全集下载
这个女生说我保持安全距离是什么意思?
新加坡过春节吗?
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?