c++实现数字的补0成定长
答案:2 悬赏:80 手机版
解决时间 2021-11-07 09:16
- 提问者网友:且恨且铭记
- 2021-11-07 01:48
c++实现数字的补0成定长
最佳答案
- 五星知识达人网友:北方的南先生
- 2021-11-07 03:08
偷懒的方法,先转成数字,再格式化字串,不知道可不可以:
#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 ) ;
}
#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 ) ;
}
全部回答
- 1楼网友:躲不过心动
- 2021-11-07 04:45
思路大概是这样子:
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);
}追问高手啊!! 我写循环到一半写不下去了,看了第一个回答的运行了下也可以
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯