c-运行时生成的printf参数



基本上,我有一个结构,它带有一些浮点变量,用于不同事物的hold inches数据。我想把这些数据转换成字符串打印出来。

例如,我想将这个浮点值"1.50"转换为这个"1 f 0.5 inches",以便在print("%s %s", convertToText(node -> data1), convertToText(node -> data2))或类似的东西中使用。但我对如何在c中实现这一点有点困惑。因此,每个"%s"都需要是"1 f 0.5 in",但要转换他的数据。

您可以找到整数,然后计算该值的mod。

float input;
float decimal;
int integer;
scanf("%f", &input);
decimal = input%;
integer = input - decimal;
printf("%i f %f inches", integer, decimal);
prtinff("%f", myFloat); 

将您的浮动直接打印到STDOUT。

char myStr[50];
sprintf(myStr,"%f",myFloat);

将浮点转换为可以使用的字符串。

可以使用strcat()连接字符串。您可以使用int()来确定浮点运算的全部部分。

您可以在string.h 下使用sprintf

 char buffer [50];
     double i=10.55;
      sprintf (buffer, "%lf ",i);
      printf ("%s n",buffer);

现在根据需要编辑字符串。有关更多信息,请参阅sprintf

为了处理适当的舍入等问题,请先乘以12,然后乘以所需的精度,然后对数字进行分段。


这避免了7.99999->7 f 12.0 inch,相反,我们得到了8 f 0.0 inch

当数字为负数时,不要重复"英寸"字段中的符号。

在超过intfloat的整个范围内工作。

#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 inchn", 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

最新更新