Confused writing this program [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
New to coding. The first part in the first link which is the character letter 'a' is correct. But then after that, its downhill from there.
Its showing me whats wrong, but I do not understand it.

You have declared several variables with the same name 'number' in the same scope. That is not allowed and leads to the error messages.

Within a scope (such as a function or loop or something), you can only declare a variable once. Otherwise, it would be ambiguous which one you were talking about.
The error is saying you've already declared a variable called number (as an int), and you cannot declare it again within the same scope.
Make the second variable called something else:
double dNumber = 1.11;
cout << "Please enter a double: " << dNumber << endl;
bool bNumber = 0;
cout << "Please enter a bool: " << bNumber << endl;
Note, it's usually more typical to set bool values to either true or false.
Now, if you really, really wanted to use the variable name number multiple times, you could put each section in curly braces:
{
double number = 1.11;
cout << "Please enter a double: " << number << endl;
}
{
bool number = 0;
cout << "Please enter a bool: " << number << endl;
}
In that case, you would no longer have access to that variable outside the curly braces, thus the reference is no longer ambiguous.

Related

How does increment work in this scenario C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I did not write this code.
i'm on my 3rd day of coding in C++ and i'm having a hard time understanding how incremnent works in general.
int main()
{
int antal_ord {};
double medellangd {};
string kort_ord;
string langt_ord;
int min_length {100};
int max_length {};
string S;
cout << "Mata in en text:\n" << endl;
while (cin >> S)
{
if (S.length() > max_length)
{
max_length = S.length();
langt_ord = S;
}
if (S.length() < min_length)
{
min_length = S.length();
kort_ord = S;
}
medellangd+=S.length();
antal_ord++;
}
if (antal_ord == 0)
{
cout << "Inga ord matades in." << endl;
}
else {
medellangd = (medellangd / antal_ord);
round(medellangd);
cout << "Texten innehöll " << antal_ord << " ord." << endl;
cout << "Det kortaste ordet var " << '"' << kort_ord << '"' << " med "
<< kort_ord.length() << " tecken." << endl;
cout << "Det längsta ordet var " << '"' << langt_ord << '"' << " med "
<< langt_ord.length() << " tecken." << endl;
cout << "Medelordlängden var "<< fixed << setprecision(1) << medellangd << " tecken.";
}
return 0;
}
antal_ord is the variable for the amount of words written in this scenario.
In the line where it says "cout << "Texten innehöll " << antal_ord << " ord." << endl;" how does it know how many words have been written? The only time this variable is used before this line is when the variable gets incremented, but how does that let the variable know how many words have been written in total?
and also the .length command, does it basically just count the amount of letters written?
There's really nothing special going on here. Every time you read one word with cin >> S, you increment antal_ord by one. Since you started with zero words written and antal_ord==0, at the end antal_ord will equal the number of words read from cin.
Similarly, S.length() returns the number of letters currently in S. In your case, that is exactly the number of letters read from cin since you didn't chance S after reading. But if you did S += " some extra letters, then S.length() will of course change.
When you'll learn about most programming languages, you'll start off with basics: syntax, data types, declarations (vars + funcs as well as other possible concepts), loops, calls, math operations and other code-control techniques relevant to each programming language.
What you'll see about most (and I;ll try to "rewind" from the generalization I started with and back down to C/C++) is that you have the following type of math operation variations when it comes to addition (let's focus on this, as it's more on point with the question).
result in a separate variable, in our case b: b = a + 1;
result in the same variable: a += 1;
incrementing the value of the variable: a++;
Expanding on it:
In the first case, b will have its value overwritten and is dependent on a different values (in this case the value of a and 1). What you need to focus on here is that a is NOT changed.
In this case, a receives a new value and is incremented by the right-side-value, in our case 1. a is changed by adding one (not incrementing)
In our case, similar to #2, the value of 8a* is updated, but the incrementation is done by 1.
Apart from syntactic sugar or code style preference, the difference between each is also in the way the variables are assigned their values (more formally said, in the assembly code "underneath"). This topic is a lot more complicated for someone that started programming, but focusing on the question, the answer is simply that ++ increments the value by 1.
Also note that there is a difference in certain coding flows between ++a and a++. Mainly in loops. For ++a the value is set before executing the code, using the already incremented value in the code, while a++ uses the current value of a first, then increments it.
Try it like this:
int i = 0;
while (++i < 100)
{
std::cout << i << std::endl;
}
... versus...
int i = 0;
while (i++ < 100)
{
std::cout << i << std::endl;
}
Then count how many lines each case wrote.
There is also a small caveat you should be aware of, it's a bit more advanced, so it's just a little "FYI" for you. There are two C++ techniques called "function overloading" and "operator (re)definition". Let's focus on the second one. You could build your own data type (for example a struct or class) and implement your own operators that do something other than what their arithmetic counterparts do. You'll see this in iterator definitions. In that case ++ is not "actual value incrementation" (so it's not a math calculation), but rather switching to the next item in a list. Once you reach std::vector lessons you'll encounter that.

Why is the int function acting strange when I set it to 500? c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I am trying to set a int to 500, but random numbers such as 22067 come out.
I am trying to make a simple gambling game. Currently, what I'm doing is that I set int gambledMoney = 500; But when I ask to print the 500, it does work but instead it prints 22067. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//introduction
cout << "Why hello human!\nWelcome to this gambling game where you... gamble!\nTo explain how to play here are the steps:\n\n";
//instructuions
cout << "You always start with $2000.\nAt the very beginning of each new round, you will be given choices on the amount of money you will gamble.\n";
cout << "Then you will gamble against an AI.\nIf you win, you gain the amount that the AI gambled...\nBut if you lose, you lose the money that you gambled.\n";
cout << "If you reach $500, you lose. Same goes with the AI.\n";
//game start
cout << "\nNow lets start!\n";
//gamble amount
string gambleChoice;
int gambledMoney;
cout << "\nHow much would you like to gamble?";
cout << "\n A) $500\n B) $750\n C) $1000\n D) $1250\n E) $1500\n F) $1750\n G) $2000\n\n";
//amount chosen
cin >> gambleChoice;
if (gambleChoice == "a")
{
int gambledMoney = 500;
}
cout << "\nYou have gambled $" << gambledMoney << "!" << endl;
return 0;
}
Does anyone know why it is not putting 500?
You are declaring two different variables with the name gambledMoney in different scopes, so that one variable "shadows" the other variable with the same name.
The line
int gambledMoney = 500;
will create a new variable with that name, and set it to 500. It won't change the value of the existing variable to 500.
You probably want to change that line to the following:
gambledMoney = 500;
That way, it will change the value of the existing variable, instead of creating a new one.
If you are using the compilers gcc or clang, I recommend that you compile with the -Wshadow command-line option. That way, the compiler will warn you when you create two variables of the same name, so that one shadows the other.
That is not the only compiler warning that I recommend enabling, though. You may want to read this for further information:
Why should I always enable compiler warnings?

When I run the program in DevC++ 5.11 TDM-GCC 4.9.2 doesn't work how I expect, but in an online compiler it just works [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 2 years ago.
I'm a newbie in the programming world, and i've decided to start with C++ code a few days ago as my first programming language.
I just started to read an online course which i'm guiding on (and aply while i'm reading it).
The course in question assigns a serie of small optional exercises, wich go hand in hand with the topic that is being dealt at that moment.
One of this optional exercises is: "Create a program that multiplies two whole numbers in the following way: it will ask the user for a first whole number. If the number that you type is 0, it will write on the screen "The product of 0 by any number is 0". If a number other than zero has been entered, the user will be prompted for a second number and the product of both will be displayed."
How it says, I did my best to coding that program.
The code of what I did is:
#include <iostream>
using namespace std;
int main ()
{
int a;
int b;
int solve;
cout << "Enter a number: ";
cin >> a;
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
}
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
return 0;
}
So, I press F9 to compile, then F10 to run it.
I proceed to testing it.
I put and different number from zero, I put another one. Throws me a multiplication of both. Nice.
I put and different number from zero, I put another one that actually its zero. Throws me the message of "else" order. Nice.
**BUT
I put and number equal to zero, and throws me the message of the "cout" order of "if (b!=0)".**
I didn't really know what I had done wrong, so, I ask for help from a friend who has some more experience than me, and tells me that actually it's nothing wrong. In fact, he proved me sending to me a screen cap of his Dev C++ with my code in it, and how it runs just how it had to be.
Then, I opened an online compiler (https://www.onlinegdb.com/online_c++_compiler#) to get down my doubts, and yes, there runs correctly too.
So, here's my question?
What's the problem? Why that happens?
I have the DevC++ 5.11 TDM-GCC 4.9.2, and I'm using the deafult compiler.
Please, I would like some of help, I feel more comfortable compiling in PC than online, it's more quick.
Thank you anyway for reading until here.enter image description here
The reason why this happens, as #TrebledJ mentioned, is that you've not initialised the variable b. So you can get over this problem just by initialising b to any value of your choice (preferrably 1 or 0 for simplicity). But there's a workaround if you don't want to initialise the values. I would transform your code to something like this:
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
Basically, what I'm doing is, if the value of a after input is 0, I'm not running the part for taking the user input of b.

Errors: expected expression and expression result unused [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have written a code that prompts the user to input a number and then tell them if it is odd or even. But it is giving me these errors that don't make sense at all.
How do you fix them?
Haven't used C++ in a while but i think it should look something like this
if(x%2 == 0)
{
std::cout << x << "is even\n";
}
else
{
std::cout << x << "is odd\n";
}
your errors are because you were basically saying
cout << x;
"is even";
which doesn't make sense to the compiler or to anyone what exactly is supposed to happen with "is even"
You should use cout << x << "is_even" instead of cout << x; "is_even";.
You get the warning about expression result unused because in your case you don't use "is even".
And the error is because after your if without {} brackets there are 2 expressions.
You can omit brackets and use else after if only if there is one expression after if.
Try adding {} around the code after if and you will get only warnings about expression result unused.

C++ If statement misbehaving [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm quite a newbie (started to learn about coding just like 2 weeks ago) and I'd really appreciate some help to explain why my code isn't working.
I wrote a simple code to calculate the probability. That's not really important part. The code requires some user input so in order to make it kinda foolproof, I wrote two if statements for various kind of wrong input (wrong data type, number too high, number too low) to throw an error message and kill the program. And if the input is right (means none of the conditions of the if statements is true), it should call a function diceTwo(des).
However, if I input number 8 - which should be allright - for some reason that I can't figure out - it triggers the number too high/low if statement, so no matter what number I enter, the function never gets called.
cin >> des;
if (cin.fail())
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid input! Use only whole positive numbers!" << endl;
cout << "Try again." << endl;
return -1;
}
if (des> 12 || des< 1);
{
cout << "Invalid input!" << endl;
cout << "Remember the only possible values are from 2 to 12!" << endl;
cout << "Try again." << endl;
return -1;
}
diceTwo(des);
cout << "The probability of this roll is " << x << "%" << endl;
This is the part that makes troubles. I already tried to split the problematic if statement into two (one for <1, one for >12), or adding a new if statement for des>1 && des<12 to call the function, none of it worked. I worked with if statements to provide foolproofness for user input few times before, always worked well, so I really can't seem to find what's wrong this time. Anyone could tell me how to fix it please?
You have a semi colon after the if statement. Look CLOSELY:
if (des> 12 || des< 1); //<----- semi colon
{
cout << "Invalid input!" << endl;
cout << "Remember the only possible values are from 2 to 12!" << endl;
cout << "Try again." << endl;
return -1;
}
The semi colon terminates the if statement, so that your program just continues to the next line, which, happens to be your invalid input line. Remove the semi-colon and you're golden :)
Mistakenly added ; in if
if (des> 12 || des< 1);