-4

I have the following :

   int R=25;
double pi=3.14;

double r=R*sqrt(rand());
cout<<"r: "<<r<<endl;
double th=2*pi*rand();
cout<<"th: "<<theta<<endl;

I want to convert : r=1.98 and th=5.08. I would also like the double result=r*th to be with 2 zecimals.

when I print double result =r*th; the number is very huge and is not realistic.

How to change the r and th value to 1.98 and 5.08? How to solve this?

I need to change each double to just 2 decimals after "."

I am working in c++ under ubuntu.

Thx appreciate

user1165435
  • 231
  • 2
  • 4
  • 11

2 Answers2

2

To produce random values in the range you specified, try this:

r = (R*(rand()/(RAND_MAX + 1.0)));
th = (2*3.14*(rand()/(RAND_MAX + 1.0)));

The expression rand()/(RAND_MAX+1.0) produces values in the range [0,1.0). Multiplying that by the range limit gives you the numbers you want.

Note: this doesn't limit the numbers to two decimal places, which is more a function of how you print them. To print them with two decimal places, try this:

std::cout << std::fixed << std::setprecision(2) << r << "\n";
std::cout << std::fixed << std::setprecision(2) << th << "\n";
std::cout << std::fixed << std::setprecision(2) << (r*th) << "\n";

See this question: C++ generating random numbers

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Using this I have the same values for r and th every time I run the program. This is not what I want. I want to have different values. – user1165435 May 09 '12 at 20:43
  • Shouldn't it be `rand() / (double)RAND_MAX`? Logically, your code can never produce `1.0`, because `rand()` can never be `RAND_MAX + 1.0`. – Puppy May 09 '12 at 20:44
  • 1
    Then you need to seed your random number generator, once per program invocation. See `srand()`. – Robᵩ May 09 '12 at 20:44
  • @DeadMG - Right, my code can never produce 1.0. I think that is what the OP desired. He never wants `2*pi`, he wants to get arbitrarily close to it. – Robᵩ May 09 '12 at 20:45
  • Can you please give me a help? How to obtain random numbers based on my desire? – user1165435 May 09 '12 at 20:48
  • @user1165435 The first code fragment in my post produces exactly what you desire, as near as I can tell. What, specifically, do you need help with? For more information about `srand()` try this: http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand – Robᵩ May 09 '12 at 21:18
0

If you need to make both numbers smaller by the same amount then you can simply divide them both by the same number. You'll lose approximately the same precision either way.

If you really want to completely alter the result by chopping off the exponent then you could probably dig into the double number format itself and separate out the mantissa.

Why you would do this is a mystery to me.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125