Here I have simple code to serve as a calculator for integers.
//Calculator, by Michael Lowry
#include <iostream>
using namespace std;
void main ()
{
int input = 0;
int input2 = 0;
int answer = 0;
int operation = 0;
cout << "Enter your first number" << endl;
cin >> input;
cout << "Type 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division" << endl;
cin >> operation;
cout << "Enter your second number" << endl;
cin >> input2;
if (operation = 1)
{
input + input2 == answer;
}
if (operation = 2)
{
input - input2 == answer;
}
if (operation = 3)
{
input * input2 == answer;
}
if (operation = 4)
{
input / input2 == answer;
}
cout << "Your answer is " <<
cout << answer << endl;
system ("PAUSE");
}
When I enter "1" for all three inputs, I get the output "Your answer is 6121DBCC0". Why is my answer variable all messed up?
Your output goes wrong. You should have
cout << "Your answer is " << answer << endl;
instead of
cout << "Your answer is " <<
cout << answer << endl;
What happens is that you are writing the outstream object cout to output.
Also the comparison operators are wrong, as others have noted. You should have == instead of = in the if-statements and vice versa in the assignment part. Like this:
if (operation == 2)
{
answer = input - input2;
}
There are several errors: this is assigning a value to the operation variable, not comparing it against something:
if (operation = 1)
it should rather be
if(operation == 1)
furthermore this doesn't assign the result of input+input2 to answer but rather makes an unused comparison evaluation
input + input2 == answer;
and it should rather be
answer = input + input2;
You should change your code accordingly. Finally this:
cout << "Your answer is " <<
cout << answer << endl;
is wrong since you're passing the cout object along (mind the operator<<). That should have been
cout << "Your answer is " << answer << endl;
Also: main() is supposed to return int.
Thus your code should have looked like:
int main () {
int input = 0;
int input2 = 0;
int answer = 0;
int operation = 0;
cout << "Enter your first number" << endl;
cin >> input;
cout << "Type 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division" << endl;
cin >> operation;
cout << "Enter your second number" << endl;
cin >> input2;
if (operation == 1) {
answer = input + input2;
}
if (operation == 2) {
answer = input - input2;
}
if (operation == 3) {
answer = input * input2;
}
if (operation == 4) {
answer = input / input2;
}
cout << "Your answer is " << answer << endl;
system ("PAUSE");
}
Try it out
First: Use
if (operation == 1)
instead of
if (operation = 1)
because == is for equality, = is for assignment.
Second:
answer = input1 + input2;
instead of
input + input2 == answer;
Do this in all if statements.
Third: Use
cout << "Your answer is " << answer << endl;
to print your answer.
And remember answer = input / input2 will give you integer division not floating point.
First mistake
If you want to assign value to variable answer you should do:
answer = input1 (required operator here) input2;
In your code such construction:
input - input2 == answer;
Is wrong in 2 ways:
If you want assign value to answer use assigning= not comparing == operator.
Assigning values goes from right to left, so your desired variable should be on the left side.
Second Mistake
In line if (val = yourConstant) you made very popular mistake - assigning inside if statement. Many languages prohibit such things, because they are hard to detect without debuggining or tests. The code inside if statement will be executed only if yourConstant will be more than 0. Instead please use if (val == yourConstant) or if (yourConstant == val).
So instead of:
if (operation = 1)
do:
if (operation == 1)
Also change your output to:
cout << "Your answer is " << answer << endl;
Another mistake:
input - input2 == answer;
This is wrong. You have to make answer equal to input - input2. Also there should only be one =, because it is not a condition.
So:
answer = input - input2;
Apply that to all your arithmetic inside the if statements. That should fix it.
But try to not use system ("PAUSE"); because it has its problems if you transfer your code. Just a suggestion.
Related
I am struggling to find a way to break down an input from the user to a location on a chess board. For example (A1). I want to make sure that they have entered a Letter between A and H and a number between 1 and 8. Not sure if comparing ASCII is the best approach?
Using C++ this is a snippet of what I have attempted. startingp is the input from the user
char startChar = startingp[0];
int SCascii = startChar;
int startInt = startingp[1];
if (!(ascii_A <= SCascii >= ascii_H) || !(1 <= startInt >= 8))
{
cout << "Your inputted move, " << startPos << ", is invalid." << endl;
cout << "Enter the coordinates of the piece you want to move. (eg A1) : ";
cin >> startingp;
cout << endl;
}
This condition:
(ascii_A <= SCascii >= ascii_H)
is not correct. Or at least, I don't think it's what you mean. Instead, do:
((ascii_A <= SCascii) && (SCascii >= ascii_H))
Other than that, your logic seems reasonable.
I made a Chess game as well, and this is what I used to get the coordinates:
Position* Interface::askPosition()
{
cout << "position: ";
string inp;
cin >> inp;
while (!(isalpha(inp[0]) && isdigit(inp[1]))) {
cout << "Please press CHAR + DIGIT\n";
cin >> inp;
}
return new Position(inp[0] - 'A', inp[1] - '1');
}
It's a static method of a class called Interface and returned a pointer to a Position object. However, this might be not a C++-clean way
You can just compare it with characters, no need to convert it into an int (ASCII).
char startChar = startingp[0];
int SCascii = startChar;
int startInt = startingp[1];
if (!(startChar>='A' && startChar<='H') || !(startInt>=1 && startInt<=8))
{
cout << "Your inputted move, " << startPos << ", is invalid." << endl;
cout << "Enter the coordinates of the piece you want to move. (eg A1) : ";
cin >> startingp;
cout << endl;
}
I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}
int main() {
power=1;
while (1 == 1){
tapcost=power*3;
cout << "type upgrade/buy/a" << endl;
cin >> way;
if (way == "upgrade"){
cout << "1. A Power " << "(Costs: " << tapcost << ")" << endl;
cin >> upgr;
if (upgr == 1){
if (0<=money-power*3){
power=power+1;
money=money-power*3;
}
else
cout << "You can't afford that!!!" << endl;
}
}
if (way == "a"){
money=money+power;
}
}
return 0;
}
When I type upgrade and then type anything else other than the variable "1", the code will repeat infinitely.
This is a never-ending problem.
See this question: Infinite loop with cin when typing string while a number is expected
I think your code have some mistakes.
int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648 / 2 147 483 647)
I suggest you to use getline, cin.getline or fgets instead of cin >> when reading a line.
And just use while(1) or while(true)
You have created an infinite loop by never changing the value of your ‘1’ variable. In some way you need to change that value when iterating through your conditions or else you’ll never get out of your loop.
You could also try out something like that.
char i;
while((std::cin >> i) && i != '1') {
....
}
In your code, while (1 == 1) creates an infinite loop. Since I assume you want this code to keep asking players for their input until they decide to stop, you can add an option exit which breaks out of the loop when the player wants to.
#include <iostream>
int main() {
int power = 1;
int money = 1000;
while (1 == 1) {
int tapcost = power * 3;
std::string way;
std::cout << "type upgrade/buy/a/exit" << std::endl;
std::cin >> way;
if (way == "upgrade") {
std::cout << "1. A Power " << "(Costs: " << tapcost << ")" << std::endl;
int upgr;
std::cin >> upgr;
if (upgr == 1) {
if (0 <= money - power * 3) {
power = power + 1;
money = money - power * 3;
}
else {
std::cout << "You can't afford that!!!" << std::endl;
}
}
}
if (way == "a") {
money = money + power;
}
if (way == "exit") {
break;
}
}
return 0;
}
I'm a beginner at programming and I'm trying to make a Kilometer and Miles converter application. I'm using codeblocks for my code. Choice 2 keeps giving me 0 as the result. Here's the exact code I'm typing:
#include <iostream>
using namespace std;
double choice, value1, result;
// I'm sure I messed up somewhere after this:
double value2 = .621371;
double value3 = 1.609344;
// Are these two lines ^ supposed to be here?
int main()
{
while (true) {
cout << "1. Kilometers to Miles" << endl;
cout << "2. Miles to Kilometers" << endl;
cout << "3. Exit the Application" << endl;
cout << "Please enter a choice: ";
cin >> choice;
if (choice == 3)
break;
cout << "Please enter the first value: ";
cin >> value1;
// This if statement keeps giving me 0:
if (choice == 2)
result = value1 * value2;
// I believe this part here is okay:
else if (choice == 3)
result = value1 / value3;
cout << "The result is: " << result << endl;
}
}
Here's how to fix your code:
1.Indent properly (Makes your code more readable)
2.This is making you code not work your code and is also very much unnecessary:
if(choice == 3) {
break;
}
3.Every single one of your if/else/else if statements need to have those curly braces after them:
if(whatever=whatever) {
//whatever
}
4. Forget about using those break statements for programs this simple.
5. You missed "Kilometers to Miles".
6. The exit option is screwed up, change
else if(choice == 3)
result = value1 / value3
to
else if(choice == 3) {
return 0; // To end the program
}
7. Don't double the choice variable, it uses much, much, much, much more data then a simple intvalue (and what if the user enters 3.1 (or 4.838389, ect.) as a input?
8. You should make the precision of your result less, (you don't want 3.37374662232365 miles/kilometers, you want 3.3 miles/kilometers.) You can do that by also adding #include <iomanip> and adding in setprecision() before the declaring what "result" is (i.e: result = setprecision(1) value1 * value2;)
9. Including the whole std namespace is inappropriate in this case (it will slow your program down ALOT), so you should write std:: before each std function, or just write using std::whatever
I fixed the Problem Now. If any one can also comment below to me, is this a lot better than my original code? Basically is this new code a lot more readable to you all and is it more organized? I would love to get y'all's opinion on this updated code.
#include <iostream>
float choice, value1, result;
int main(){
while (true){
std::cout << "Please enter a choice: " << std::endl <<
"1. Kilometers to Miles" << std::endl <<
"2. Miles to Kilometers" << std::endl <<
"3. Exit the Application" << std::endl;
std::cin >> choice;
if(choice == 3){
break;
}
std::cout << "Enter the Value you would Like to Convert: ";
std::cin >> value1;
if (choice == 1){
result = value1 * 0.62137;
}
else if (choice == 2){
result = value1 * 1.609344;
}
std::cout << "The result is: " << result << std::endl;
}
}
is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}