如何在Objective-C中创建一个随机的浮点数? [英] How to create a random float in Objective-C?

查看:137
本文介绍了如何在Objective-C中创建一个随机的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Objective-C中创建一个在0.15和0.3之间的随机float。以下代码总是返回1:

  int randn =(random()%15)+15; 
float pscale =(float)randn / 100;

我做错了什么?

解决方案

试试这个:

pre $(float)rand()/ RAND_MAX

或者在0到5之间得到一个:

  float randomNum =((float)rand()/ RAND_MAX)* 5; 

几种方法可以做同样的事情。


I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:

int randn = (random() % 15)+15;
float pscale = (float)randn / 100;

What am I doing wrong?

解决方案

Try this:

 (float)rand() / RAND_MAX

Or to get one between 0 and 5:

 float randomNum = ((float)rand() / RAND_MAX) * 5;

Several ways to do the same thing.

这篇关于如何在Objective-C中创建一个随机的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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