Advertisement
Guest User

Probability2

a guest
Aug 4th, 2012
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. using namespace std;
  6. //function prototype
  7. void getHits(int arr[], int n);
  8. float getProbability(int num, int count);
  9. //global variable (*evil*) probability array
  10. float probability[6];
  11. int main(int argc, char* argv[]){
  12.  
  13. //declare hits array
  14. int hits[6] = {0,0,0,0,0,0};
  15. //initialize number of trials
  16. int n;
  17. cout << "input number of trials"<< endl;
  18. cin >> n;
  19. //call to getHits()
  20. getHits(hits, n);
  21. //output probability
  22. for(int i = 0; i <6; i++){
  23. cout << "number of hits for J" << i + 1<< " is " << probability[i] << endl;
  24. }
  25. system("PAUSE");
  26. return 0;
  27. }
  28. /*getHits() takes an array arr[] and increments a cell by 1 when its corresponding statement evaluates to true and goes through the loop n times*/
  29. void getHits(int arr[], int n){
  30. int irandomNumber ;
  31. float randomNumber;
  32. //seed for psuedo-random numbers
  33. srand(time(NULL));
  34. for(int i = 0; i < n; i++){
  35. irandomNumber = rand()% 7;//we generate random numbers between 0 and 7
  36. randomNumber = static_cast<float>(irandomNumber)/6.0f;//a random hit probability
  37. /*check for hits*/
  38. if(randomNumber >= 0 &&randomNumber <= (1.0f/6.0f)) arr[0]++;
  39. if(randomNumber >= (1.0f/6.0f) && randomNumber <= (2.0f/6.0f))arr[1]++;
  40. if(randomNumber >=(2.0f/6.0f) && randomNumber <= (3.0f/6.0f)) arr[2]++;
  41. if(randomNumber >= (3.0f/6.0f )&& randomNumber <=(4.0f/6.0f)) arr[3]++;
  42. if(randomNumber >= (4.0f/6.0f) && randomNumber <= (5.0f/6.0f)) arr[4]++;
  43. if(randomNumber >= (5.0f/6.0f) && randomNumber <= 1) arr[5]++;
  44. }
  45. for(int i = 0; i < 6; i++){
  46.     //calculates probability and assigns it to probability array
  47. probability[i] = getProbability(arr[i], n);
  48. }
  49. }
  50.  
  51. /*calculates probability by dividing num with count and returns the result*/
  52. float getProbability(int num, int count){
  53. return float((float)num/count);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement