I'm currently working on a couple of programs. The first deals with binary numbers. I'm supposed to take the number that is inputed and then pick off each digit, which I know how to do. Then, I am supposed to take each digit (and only if it is a 1 or a 0) and convert the whole thing to binary. Which, again, I know how to do. My only issue is with figuring out how to use the while and/or if statement to only do this if the numbers are all 1s or 0s. Here's my code so far:
Code:
#include <iostream>
using namespace std;
int main() {
int digit, eval, num1, num2, num3, num4, num5, digit5, digit4, digit3, digit2, digit1, sum;
cout << "Enter a Binary Number: ";
cin >> digit;
cout << " " << endl;
num1 = (digit / 10000) % 10;
num2 = (digit / 1000) % 10;
num3 = (digit / 100) % 10;
num4 = (digit / 10) % 10;
num5 = (digit / 1) % 10;
digit5 = num5 * 1;
digit4 = num4 * (2 * 1);
digit3 = num3 * (2 * 2);
digit2 = num2 * (2 * 2 * 2);
digit1 = num1 * (2 * 2 * 2 * 2);
sum = digit5 + digit4 + digit3 + digit2 + digit1;
cout << "\n";
cout << "The decimal equivalent of " << digit << " is " << sum;
cout << "\n";
system("pause");
return 0;
}
It's messy, but outside of the fact it works no matter what numbers are input, it works.
OK, so that's that. Now I'm working on another program, where I accept input from the user in regards to mileage and gallons. I'm supposed to prompt the user to input their mileage and gallons for a trip, and then, based on that, display the MPG. Also, I am supposed to put up a total that displays beneath the MPG that is basically each MPG reported divided by the number of MPG input. Finally, I am supposed to make the program so that it quits if the user enters -1. Here's my code for that so far:
Code:
#include <iostream>
using namespace std;
int main() {
int i, mileage, gallons, mpg, total;
i = 1;
total = 0;
while (i <= 1) {
while (mileage != -1) {
cout << "Enter Mileage for Trip #" << i << " : ";
cin >> mileage;
cout << "Enter Gallons for Trip #" << i << " : ";
cin >> gallons;
cout << "\n";
mpg = mileage / gallons;
cout << "MPG for Trip #" << i << " : " << mpg;
cout << "\n";
total = (total + mpg) / i;
cout << "\n";
cout << "Total so far: " << total;
cout << "\n";
i = i + 1 ;
}
}
cout << "\n";
cout << "Thanks for using our program!";
system("pause");
return 0;
}
How can I get the while loop to work in the way I need it to work? I appreciate any suggestions.