Hi,

I have a question regarding a program I'm writing in C. I have a few variables which I would like to assign a random number to. However the sum of all the numbers I assign should equal 1. I have not been able to find a way to do this. Any suggestions would be appreciated!

Thanks in advance.

So you are looking for the logic right?

Get the number of variables, Lets call this N

then 1/N = Lets say this is X.

so you want the to loop N-1 times and get the Decimal Random number Where Max is X.

and then you want the Nth to equal 1-(all your variable Except the Nth Value)

Enjoy

Hey thank you so much. That sounds like it should do the trick!
:)

You may try adding up to lets say 100 and then divide all the values by 100 and assign them to the variables. Like;

a=25 b=30 c=40 d=5 adds up to 100.

var1=25/100
var2=30/100
....

If you get stuck post here again.

Kolay gelsin =)

Tesekkurler :) I will give these replies a try! :) Thanks guys.

Tellalca Brilliant man, why reinvent the wheel.

any tips on using the rand() function with float numbers?:$ Ive tried :

datapoint[j].membership_value=rand()%x;

where x is a float and membership_value is a float however I get the error:

'%': illegal, right operand has type float.

Ive looked through many forms and tried what has been posted but nothing seems to work.

Thanks for the help!

yasemin that's what Tellalca is telling you.

Use Rand get an int to max 100 and divide it by 100.

You will get decimals.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.