I'm guessing this was some type of homework assignment to calculate with loops, yes?
You had one overarching issue which was not resetting the values before you used them later in a different context. When you used your done boolean, it became true after the first loop, but you never reset it to false before you try to take the input for your product calculation. So, what was happening was the program was completely skipping lines 57-69 because your
while(!done)
was evaluating itself to false immediately and skipping the input. Then your default zeros you put for the input values d and e.
Also take a look at the starting and ending values for your second loop. Do you want and inclusive range or exclusive? Meaning, if I say whats the range between 1 and 5 and your program returns 5 because it counted 1,2,3,4, and 5. That means that range would be inclusive. If you wanted exclusive you would get 3 because your range would be counting only the numbers between your end two numbers, not the end numbers themselves. For example, if you want the exclusive range of 1-5 it would count the 2,3, and 4 but not 1 and 5. Your answer is 3 with that kind of a range. Figure out whichever one you're looking for and adjust your values to match. You seem to have a pretty good grasp on this already!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int num;
int product;
bool done = false;
int a = 0;
while (!done)
{
cout << "Please input an integer greater than or equal to 1: ";
cin >> a;
if (a > 0)
{
done = true;
}
else
{
done = false;
}
}
for (int i = 1; i <= a; i++)
{
sum = sum + i;
}
cout << "The sum of integers from 1 to " << a << " is: " << sum << endl;
cout << endl;
int b, c;
cout << "Please enter two integers: " << endl;
cin >> b >> c;
if (b > c)
{
int x = c;
c = b;
b = x;
}
sum = 0;
int count = b; //Depending on what kind of interval you're talking about you can add or subtract 1 from the beginning and end values to get your desired range.
while (count < c+1)
{
sum++;
count++;
}
cout << "The interval between " << b << " and " << c << " is: " << sum << endl;
cout << endl;
int d = 0;
int e = 0;
done = false; //You have to reset your boolean values before re-using them.
while (!done)
{
cout << "Please enter two integers, the second must be non-negative: ";
cin >> d >> e;
if (e < 0)
{
done = false;
}
else
{
done = true;
}
}
if (e == 1)
{
product = d;
}
else if (e == 0)
{
product = 1;
}
else
{
int i = e;
do
{
if (i == e)
{
product = d * d;
}
else
{
product = product * d;
}
i--;
} while (i > 1);
}
cout << "The product of " << d << "^" << e << " is : " << product << endl;
return 0;
}
|