基本上我有一个带有一些浮点变量的结构,用于保存不同数据的英寸数据。我想将此数据转换为字符串以便打印出来。
我希望将此浮动值"1.50"
转换为此"1 f 0.5 inches"
,以便在print("%s %s", convertToText(node -> data1), convertToText(node -> data2))
或类似内容中使用。但我对如何在c中实现这一点感到困惑。因此,每个"%s"
都需要"1 f 0.5 in"
,但他的数据已经转换。
答案 0 :(得分:1)
你可以找出整数,然后计算值的mod。
float input;
float decimal;
int integer;
scanf("%f", &input);
decimal = input%;
integer = input - decimal;
printf("%i f %f inches", integer, decimal);
答案 1 :(得分:0)
prtinff("%f", myFloat);
将您的浮动直接打印到STDOUT。
char myStr[50];
sprintf(myStr,"%f",myFloat);
将float转换为可以使用的字符串。
您可以使用strcat()来连接字符串。您可以使用int()来确定float的整个部分。
答案 2 :(得分:0)
您可以在sprintf
string.h
char buffer [50];
double i=10.55;
sprintf (buffer, "%lf ",i);
printf ("%s \n",buffer);
现在可以根据需要编辑字符串。 有关详细信息,请参阅sprintf
答案 3 :(得分:0)
为了应对正确的舍入等,首先乘以12,然后乘以所需的精度,然后将数字分段。
这可以避免7.99999
- > 7 f 12.0 inch
,而我们得到8 f 0.0 inch
当数字为负时,请勿在“英寸”字段中重复该标记。
在超过float
的整个int
范围内工作。
#include <math.h>
int printf_feet_inches_tenths(float distance) {
double d = round(distance * 12.0 * 10); // convert to exact 1/10 of inch
double inch_tenths = fmod(d, 12 * 10);
double feet = (d - inch_tenths) / (12 * 10);
return printf("%.0f f %.1f inch\n", feet, fabs(inch_tenths) / 10);
}
void printf_feet_inches_tenths_test(void) {
printf_feet_inches_tenths(7.5);
printf_feet_inches_tenths(7.999);
printf_feet_inches_tenths(-1.5);
printf_feet_inches_tenths(1e30);
}
输出
7 f 6.0 inch
8 f 0.0 inch
-1 f 6.0 inch
1000000015047466219876688855040 f 0.0 inch