Promotion rules ... why no float?

Andrea Fontana via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 6 08:38:59 PDT 2016


On Tuesday, 6 September 2016 at 15:00:48 UTC, Sai wrote:
> Thanks for the replies.
>
> I tend to use a lot of float math (robotics and automation) so 
> I almost always want float output in case of division. And once 
> in a while I bump into this issue.
>
> I am wondering what are the best ways to work around it.
>
>     float c = a / b;     // a and b could be integers.
>
> Some solutions:
>
>     float c = cast!float(a) / b;
>     float c = 1f * a / b;
>
>
> Any less verbose ways to do it?
>
> Another solution I am thinking is to write a user defined 
> integer type with an overloaded division to return a float 
> instead and use it everywhere in place of integers. I am 
> curious how this will work out.

Exotic way:

import std.stdio;

float div(float a, float b) { return a / b; }

void main()
{
	
	auto c = 3.div(4);
	writeln(c);
}





More information about the Digitalmars-d mailing list