我需要将文件中的-51.235
分开并将其设置为 - ,51,.235我的问题是当我尝试从文件中读取它并将其打印在代码块中时我可以把它放进去作为一个int和浮动同时所以我可以减去int(51)和浮点数(51.235),我如何分隔我把它作为一个字符的符号?这就是我到目前为止所拥有的
if (comand == 'S')
{
fscanf(entrada, "%d %f",&y, &a);
printf("\n\nthe separate number is: %d , %f",y,a);
}
它给了我:单独的数字是:-51
,0.235000
(我怎样才能消除最后的3个零?)
在记事本中显示:
S -51.235
答案 0 :(得分:1)
只有几步:
-
-
,否则删除。)所有这一切都在一行:
float num = -51.235555;
printf("%c %d %.3f", ((num > 0.0 ) ? ' ' : '-'), (int)num, (num - (float)((int)num)));
答案 1 :(得分:1)
你可以这样做:
#include<stdio.h>
#include<math.h>
int main(void)
{
float num = -51.235;
char sign;
int intpart;
float floatpart;
sign=(num>=0.00f)?'+':'-';
intpart=floor(fabs(num));
floatpart=fabs(num)-intpart;
printf("%c,%d,%g",sign,intpart,floatpart);
return 0;
}
答案 2 :(得分:0)
问题:它给了我:单独的数字是:-51,0.235000(我怎样才能消除最后的3个零点?)
回答最后消除3个零点?
printf("\n\nthe separate number is: %d , %.3f",y,a);
答案 3 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char getChar(char **p){
return *(*p)++;
}
void skipSpace(char **p){
while(isspace(getChar(p)));//skip space char
--(*p);//unget
}
char getSign(char **p){
if(**p=='+' || **p=='-') return *(*p)++;
return ' ';
}
void getNatural(char **p, char *buff){
while(isdigit(**p))
*buff++=*(*p)++;
*buff='\0';
}
void getFloatPart(char **p, char *buff){
char point;
point = getChar(p);
if(point != '.'){
*buff = '\0';
} else {
*buff++ = point;
getNatural(p, buff);
}
}
void separate_float(char **p, char *sign, char *int_part, char *float_part){
skipSpace(p);
*sign = getSign(p);
getNatural(p, int_part);
getFloatPart(p, float_part);
}
int main(){
char line[128]="S -51.235";
char *p = line;
char command;
char sign, int_part[32], float_part[32];
command = getChar(&p);
if(command == 'S'){
separate_float(&p, &sign, int_part, float_part);
printf("%c,%s,%s\n", sign, int_part, float_part);//-,51,.235
printf("%d %g\n", atoi(int_part), atof(float_part));//51 0.235
}
return 0;
}