1

As the title says, this code is meant to calculate the probability of 2 people having the same birthday in a group of 5 but it just outputs 1, I'm fairly new to C++ so any help would be appreciated.

#include <iostream>
using namespace std;
int main(){
float p;

p=1-(364/365)*(363/365)*(362/365)*(361/365);
cout<<p;
}

Johny Jim
  • 15
  • 3

3 Answers3

2

Put a .0 on each number, that way is treated as a double instead of an integer. Integer division (364/365) equals 0

p=1.0-(364.0/365.0)*(363.0/365.0)*(362.0/365.0)*(361.0/365.0);
2

This is because after calculation 364/365 the calculates answer is an integer which is 0.

To make it work change it like this.

p=1-(364/365.0)*(363/365.0)*(362/365.0)*(361/365.0);
M Hamza Razzaq
  • 432
  • 2
  • 7
  • 15
1

You need to cast the integers to floats as / rounds to the largest integer below the result when both types are int:

p=1-(float(364)/float(365))*(float(363)/float(365))*(float(362)/float(365))*(float(361)/float(365));
Ash
  • 4,611
  • 6
  • 27
  • 41