Home > Mobile >  Ada: operator with type conversion and rounding
Ada: operator with type conversion and rounding

Time:10-04

I have a specific problem that I got some issues figuring out. I want to create an operator in Ada that can divide a float value with a character and then return as an integer.

I understand that the operator should be a function with "/" and some kind of type conversion from float value and a character to an integer. But how would the return value look like and which rounding of the float value would be appropriate?

update.

Let's say I would like to put in the float value -21.8 and the character '2'. The answer should be -11. I created a subprogram for this but I feel like the solution could be something more simple.

      function "/"(Float_Val : in Float;
        Ch      : in Character) return integer is
      
   begin
      if Float_Val < Float(0) then return
    (Integer(Float'Rounding(Float_Val)) - (Character'Pos(Ch) - (Character'Pos('0')))   1) / (Character'Pos(Ch) - (Character'Pos('0')));
      else return
    (Integer(Float'Rounding(Float_Val))   (Character'Pos(Ch) - (Character'Pos('0'))) - 1) / (Character'Pos(Ch) - (Character'Pos('0')));
      end if;
   end "/";

and "/" is called in my main program by

 Put(Float_Val / Ch, Width => 0);

CodePudding user response:

I wouldn’t want to call this weird function "/", but if you must ... the skeleton body would be

function "/" (L : Float; R : Character) return Integer is
begin
   -- this is where the magic happens
end "/";

I don’t see why you’d need to round L.
Without a bit more explanation as to what algorithm you want to use, that’s all I can say.

Update:

This seems to work quite well:

   function "/" (L : Float; R : Character) return Integer
   with Pre => R in '1' .. '9'
   is
   begin
      return Integer (L) / (Character'Pos (R) - Character'Pos ('0'));
   end "/";

See ARM 4.6(33).

CodePudding user response:

To answer your question about rounding, and to fill in the "magic" in Simon's answer, you must explain better what you want to compute. For example, what should the result of 4.567 / "A" be? And what would do you do to compute it by hand?

CodePudding user response:

Sounds to me like you want to translate something from a poor type language to the rich type language Ada. If you like to do this the Ada way it will require some reverse engineering to find out what the types ‘integer‘, ‘float’, and ‘character‘ really means. Then I guess an explaining name for ‘/‘ will emerge.

  • Related