Thursday, June 2, 2022

[SOLVED] Turning an unsigned integer into a double from 0 to 1. Dividing by integer limit not working

Issue

So I'm wanting to turn an unsigned integer (Fairly large one, often above half of the unsigned integer limit) into a double that shows how far it is between 0 and the unsigned integer limit. Problem is, dividing it by the unsigned integer limit is always returning 0. Example:

#include <iostream>
;
int main()
{
    uint64_t a = 11446744073709551615
    double b = a / 18446744073709551615;
    std::cout << b;
};

This always returns 0. Is there an alternative method or a way to fix this one? If it means anything, I'm using GCC with the -O3 optimisation flag.


Solution

You have to convert the expression on the right to double, for example, like this:

double b = static_cast<double>(a) / 18446744073709551615;

or

double b = a / 18446744073709551615.0;



Answered By - Alex A.
Answer Checked By - Katrina (WPSolving Volunteer)