浮点到字符串:字符串长度问题 [英] Float to String: Problem with string length

查看:51
本文介绍了浮点到字符串:字符串长度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将浮点值转换为字符串并创建以下简短示例:

I would like to convert a float value to a String and created the following short example:

with Ada.Text_IO;

procedure Example is
   A : constant Float := -1.234;
   B : constant Float := 123_456.789;
   C : constant Float := 987.654_321;

   package Float_IO is new Ada.Text_IO.Float_IO (Num => Float);

   String_Float_A : String := "     ";
   String_Float_B : String := "          ";
   String_Float_C : String := "       ";
begin
   Ada.Text_IO.Put_Line (Float'Image (A));
   Ada.Text_IO.Put_Line (Float'Image (B));
   Ada.Text_IO.Put_Line (Float'Image (C));

   Float_IO.Put
     (To   => String_Float_A,
      Item => A,
      Aft  => 2,
      Exp  => 0);

   Float_IO.Put
     (To   => String_Float_B,
      Item => B,
      Aft  => 2,
      Exp  => 0);

   Float_IO.Put
     (To   => String_Float_C,
      Item => C,
      Aft  => 2,
      Exp  => 0);

   Ada.Text_IO.Put_Line (String_Float_A);
   Ada.Text_IO.Put_Line (String_Float_B);
   Ada.Text_IO.Put_Line (String_Float_C);
end Example;

我的问题:我需要在调用过程 Put 之前创建足够长度的字符串变量.这如何在运行时动态完成?基本上我需要弄清楚点之前的位数.那么足够的字符串长度将是:1(符号)+ Number_Of_Dots + 1(十进制分隔符)+ Aft.

My problem: I need to create the string variables before the call of the procedure Put with a sufficient length. How can this be done dynamically at runtime? Basically I need to figure out the number of digits before the dot. Then a sufficient string length would be: 1 (sign) + Number_Of_Dots + 1 (decimal separator) + Aft.

推荐答案

十进制数点之前的位数可以通过计算 1 加上常用对数(以 10 为底)的整数部分来计算数字的整数部分.

The number of digits before the dot of a decimal number can be computed calculating 1 plus the integer part of the common logarithm (base 10) of the integer part of the number.

在艾达:

    N := Integer (Float'Floor (Log (Float'Floor (abs X), 10.0))) + 1;

您的程序必须使用 Ada.Numerics.Elementary_Functions.如果数字是负数,则必须为减号添加一个空格.

Your program must be with'ed with Ada.Numerics.Elementary_Functions. You must add a space for the minus sign if the number is negative.

如果整数部分为 0,则此公式无效,但此时 N 显然为 1.

This formula does not work if the integer part is 0, but then N is obviously 1.

这篇关于浮点到字符串:字符串长度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆