Calculations not working correctly in a number guessing program

Viewed 45

I am working on my first real program right now, which is a birthday guessing program that asks you if your birthday is shown in a set of numbers, and there are 5 sets total. Our professor gave us this piece of the program:

#include <string>
using namespace std;
int main()
{
int answer1, answer2, answer3, answer4, answer5;
cout<< "Is your birthday in Set1?\n" ;
cout << " 1 3 5 7\n" <<
" 9 11 13 15\n" <<
"17 19 21 23\n" <<
"25 27 29 31" << endl;
cout<< "\nEnter 0 for No and 1 for Yes: " ;
cin >> answer1;

I changed the code a little bit to add the math to calculate which date it is, but it seems like it has little to no affect on the output of the program, it seems that it either comes out as 1 or 31. I will attach the code here:

#include <cmath>

int main()
{
    int a = 0, b = 0, c = 0, d = 0, e = 0, K = 0;
    int Yes = 1, No = 0;
    std::cout << "State 1 for 'Yes' or 0 for 'No', if your birthday is in the set\n";
    std::cout << "Set 1: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31\n";
    std::cin >> a;
    int f = pow(a*2,0);
    std::cout << "State 1 for 'Yes' or 0 for 'No', if your birthday is in the set\n";
    std::cout << "Set 2: 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31\n";
    std::cin >> b;
    int g = pow(b*2,1);
    std::cout << "State 1 for 'Yes' or 0 for 'No', if your birthday is in the set\n";
    std::cout << "Set 3: 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31\n";
    std::cin >> c ;
    int h = pow(c*2,2);;
    std::cout << "State 1 for 'Yes' or 0 for 'No', if your birthday is in the set\n";
    std::cout << "Set 4: 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31\n";
    std::cin >> d;
    int i= pow(d*2,3);
    std::cout << "State 1 for 'Yes' or 0 for 'No', if your birthday is in the set\n";
    std::cout << "Set 5: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n";
    std::cin >> e;
    int j = pow(e*2,4);;
    K = (f+g+h+i+j);
    
    std::cout << " Your number is " << K << "!\n";
}

I've tried to change how the pow function is working here, but to no avail (and I might have just messed something up) but I'm not quite sure. As an example, for a 30th birthday, you would input 0, 1, 1, 1, 1. The program outputs 31 as the day, which would be wrong because 31 is in set 1, which I said the day was not in. If anyone can help, even a little bit, it would be greatly appreciated! Thank you!

1 Answers

What do you think the value of pow(0, 0) should be? It's clear from your code that you think it should be 0, but the actual result is 1.0 and that is why your calculation is out by one.

In any case it's a bad idea to use pow for integer exponents, because of the potential for rounding errors. In fact C++ has a simple way to calculate non-negative integer powers of 2. Just replace (for example)

int j = pow(e*2,4);

with the left shift operator

int j = e << 4;

Make this change throughout your code and your program works.

Related