Generate random double number in range [0, 1] in C

前端 未结 2 1642
自闭症患者
自闭症患者 2020-12-12 08:30

I have to generate random double number in between 0 and 1. How can i do this using C? I\'ve tried to generate an integer number between 0 and one million and then divide th

2条回答
  •  不思量自难忘°
    2020-12-12 08:58

    Be careful while dividing numbers: when both numbers are integers, the integer division will be used (in this case always resulting in zero).

    In order to have a double as a result, you need to force the division to be the division for doubles, which you can achieve by typecasting one of the numbers as a double:

    a/b => integer division (when b is larger than a you end up with zero)
    
    ((double)a/b) => floating point division (this is what you are looking for)
    

提交回复
热议问题