Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
January 4th, 2003, 12:18 PM
 Fullest_Empty
Junior Member

Join Date: Jan 2003
Posts: 1
Time spent in forums: < 1 sec
Reputation Power: 0

Would someone be so kind as to tell me the codes used in the addition of decimal numbers? Like, the variables and such.. o_O.. please? I've asked a few people this question before, and they give me this kind of coding:
float a;
float b;

a = 5.5
b = 6.3

printf("%f\n", (a + b));

But I need the program to randomly choose decimal numbers and add them together (so I can't define the decimals beforehand). The numbers have to be between 1 and 100. Any ideas? Thanks.
oO;;

#2
January 4th, 2003, 05:18 PM
 nate
Junior Member

Join Date: Jan 2003
Posts: 3
Time spent in forums: < 1 sec
Reputation Power: 0
try using the rand() function to generate your decimal values and then using another rand() function to generate the Integer portion of the value. (All you have to do to keep it as a decimal is divide the result by 100 and store it into your "float" variable). Then all you need to do is add the decimal portion to the integer portion and you have a fully randomly generated decimal number.

If you want TRULY random numbers then you have to use srand(seed)...where seed is some integer value that you have to supply which will generate a different random number.

Play around with these two functions.

#3
January 4th, 2003, 06:13 PM
 vpopper
Contributing User

Join Date: Jun 2000
Location: Southern California
Posts: 73
Time spent in forums: 56 m 9 sec
Reputation Power: 14

Code:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int myrand(int k)
{
double x = RAND_MAX + 1.0;
int y = 1 + rand()*(k/x);
return(y);
}

int main(int argc, char** argv)
{
int a;

srand( (unsigned)time(NULL) );
a = myrand(100) + myrand(100);
printf("a = %d\n", a);

return EXIT_SUCCESS;
} ```

 Viewing: Dev Shed Forums > Programming Languages > C Programming > You click here now!