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 months ago.
Improve this question
for (unsigned int i = 0; i < list.size(); i++) {
if (list.at(i) = n) {
cout << "True";
return 0;
}}
I was wondering why this would not work I understand that tou should use list.at(i) == n.
However i thought that a single = means assigning, and a double == means equal to. I understand it is different but wouldn't using only one = still be correct when using it in an if statement?
It would not necessarily be correct. When you use an assignment expression as a boolean for integers, it will return true if the integer is not zero, and it will return false if the integer is zero.
Suppose our list looks like this: 1, 2, 0, 5. Now, suppose we have this if-statement:
if (list.at(0) = 1) {
cout << "True";
}
Since the 1 in list.at(0) = 1 is not 0, the if-condition will be satisfied. If we used ==, it would be satisfied since the first value is indeed 1.
Now let's suppose we have this if-statement:
if (list.at(1) = 3) {
cout << "True";
}
The "True" would be printed because 3 is not equal to 0. However, if we replaced = with ==, the "True" would not be printed since the second value is not 3.
Let's look at one last example.
if (list.at(2) = 0) {
cout << "True";
}
This would not print out "True" since we are assigning list.at(2) to 0. However, if we replaced the = with ==, the "True" would be printed since the third value in the list is actually 0.
This shows that = cannot be used as ==.
P.S. And, if you wanted to use the list later, your list would be modified into a different list.
if (condition) {
// block of code to be executed if the condition is true
}
Here is your code list.at(i) = n is an assignment and not a condition. Seeing your code I can say that you want to check if any value in the list is equal to n or not if it is then you want to print True.
So to do this you have to use a condition if(list.at(i)==n).
For more information read about condition statements, comparison operators, and assignment operators.
Related
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 8 months ago.
Improve this question
basically I have this function repeat I understand what it does, what I don't understand is the this part of the condition in the for loop v ? sizeof(g) / 8 : 0, if someone could explain it me I would appreciate a lot because I don't get what it does.
program:
char g[1024];
double *repeat(double *v) {
for (int i = 0; i < (v ? sizeof(g) / 8 : 0); i++)
{
if (v[i] > 2 * i)
v[i] = i;
else
v[i] = 0;
}
return v;
}
int main()
{
double *t;
*t = 2.0;
t = repeat(t);
printf("Numero: %f\n",*t);
return 0;
}
This is somewhat obscure code, as illustrated by the number of incorrect attempts at answers. The key here is that the ?: operator makes an expression, that is, it's code that produces a value. So, first look at the value of the expression:
(v ? sizeof(g) / 8 : 0)
where v is a pointer. When a pointer is used in a context that expects a boolean value, the value is true if the pointer is not a null pointer, and false if it is. So, you could think of this expression as
(v != nullptr ? sizeof(g) / 8 : 0)
This expression is the upper bound of the for loop. The loop will execute for as long as i < (v ? sizeof(g) / 8 : 0) is true. So, if v is a null pointer, the condition is i < 0, which is false, and the body of the loop will not be run. If v is not a null pointer, the condition is i < sizeof(g)/8, and the body of the loop will be run as many times as whatever that value is.
If v is true, then sizeof(g) / 8 gets executed. If v is false, then 0 gets executed
If the input parameter v is not NULL, then we compare i to the result of sizeof(g) / 8 (64 in this particular case); otherwise we compare i to 0.
The following code would be equivalent (and probably a little easier to understand):
int count = 0;
if ( v )
count = sizeof g / 8;
for ( int i = 1; i < count; i++ ) { ... }
Since you say in a comment you are confused because v is a pointer, not a boolean — and yet is used in a condition:
Since the beginning of C++ there is a well-defined automatic conversion of pointers to booleans which is defined exactly for this use case of testing whether a pointer is null instead of the wordy if(p != 0 ). The latter is more complicated hence more error prone:
OK, we compare against a null pointer (in C++ a literal zero was the only null pointer literal before the introduction of nullptr).
OK, we test for inequality.
OK, two negations (null pointer and inequality) make for a positive: Is the pointer there? I think that's what it is. I'm tired. Let's be sure and play it through in our minds. I have a valid pointer. It is not equal to 0. Inequality therefore returns false. The false result indicates it's a valid pointer. I think this is what I wanted, right? Where was I?
Instead , you simply write if(p). no comparison, no double logic inversion, it couldn't be simpler: If the pointer is there, do something with it ;-).
i < (v ? sizeof(g) / 8 : 0)
This is the equivalent of saying this shorthand:
if(v){
i < sizeof(g)/8;
}else{
i < 0;
}
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 2 years ago.
Improve this question
I have been working to code, a calculator, that works with recursion.
Input: ! + 1 3
code will do 1+3 and then take the faculity of the sum
output: "24"
I finished writing the basic code( not having filtered out wrong user-input yet),
when I build it shows no warnings, but once I run it I get thrown with the 'std::out_of_range' warning. I tried around and nailed the problem down to one function, but I am unable to identify whats wrong exactly.
//Calculation
string Rechner::berechne(vector <string> t) //Calculator::calculate
{
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
if( t.at(i) == "+" || t.at(i) == "*" || t.at(i) == "!") //finds the last operator
{
t.at(i) = differenziere(i, t); //switches out the last operator with
//the result of the operation (differenziere(i, t)
if ( t.at(i) == "!")
{
t.pop_back(); // delets last element of vector and
berechne(t); // searches for the next Operator
}
else
{
t.pop_back(); //delets last two elements
t.pop_back();
berechne(t); //searches for next operator
}
}
}
return t.at(0); //when there is no more operator left, this returns the Result of the whole operation
}
For example
input: 5
the output should be 5, because there is no more operator, but i get the out_of_range warning.
input: + 1 3
has the same output of the warning.
So my best guess is, once the vector consists out of one string, for some reason this falls into the if function, what doesn't make sense to me.
Input is a string, that I convert to a vector. This works all fine, i have tested that.
I am working with code::blocks, c++11 and on a windows laptop.
I hope you can help me.
Also please excuse my english, it's not my native language. I speak fluet normally, but I haven't been around the topic of coding for long, so this is s a little different for me.
i >= 0 will be always true because i is unsigned.
Instead of this
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
You can do
for (unsigned int i_loop = t.size(); i_loop > 0; i_loop--) //searches the vector starting from the back
{
unsigned int i = i_loop - 1; // i_loop is positive here thanks to the loop condition
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 6 years ago.
Improve this question
I have this code:
#include <stdio.h>
int main(){
char s1[30] = "This is a sentence";
for(int i = 0; i<sizeof(s1);i++){
if(s1[i] = ' '){
printf("+");
}
}
return 0;
}
When I try to loop the array to find all the spaces this happens:
Output: ++++++++++++++++++++++++++++ //30 pluses.
Why doesnt my program outputs 3 pluses?
EDIT: My problem was a simply typo mistake, If you didn't understand what is wrong here take a look at accepted answer.
Change = to == in your if statement.
In your conditional statement, you're assigning space to s[ i ] (operator =). You want to compare them (operator ==).
Try
if (s[ i ] == ' ')
s[ i ] = ' ' is always true because the result of an assignment is the value assigned (space). This value is implicitly converted to a bool (0 = false, anything else = true). Since a space is 32 in ASCII, it will always be true.
References - Assignment Operator, Comparison Operators, ASCII Table
Do this:
if(s1[i] == ' '){
printf("+");
}
= is an assignment operator. To compare two value you need to use == operator. You have used = that that assignment operator always return true so + is being printed out all the time.
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 6 years ago.
Improve this question
I have a task to make a code which will write 100 first numbers of an equation (or a function, I don't know what this is)
A(n) = (A(n-1))^2 -n*A(n-2) where A(1) = 1 and A(2) = 1
It has to be solved recursively. I have written this code so far
#include <iostream>
using namespace std;
int rekurzija(int n){
if(n=1){
return 1;
}
if(n=2){
return 1;
}
if(n>2){
return rekurzija(n-1)*rekurzija(n-1)-n*rekurzija(n-2);
}
}
int main(){
for(int n=1;n<101;n=n+1){
cout << rekurzija(n) << endl;
}
}
The problem is that the program returns 1 hundred times instead of 1,1,-2,0,...(instead of actually solving this function). What is wrong in this code?
You are using simple assignment operator = instead of Is equals to relational operator == in your rekurzija() function for if conditions
if(n = 1) //here `n = 1`is an assignment statement
{
//something...
}
What happens if you use = instead of ==?
The if condition will always evaluate to be true if the assigned value in the assignment statement is non-zero number.
Note: An assignment to zero evaluates to be false i.e, for if(n = 0), the if block will not be entered. You don't have any such if blocks in your code.
So your first if is always evaluated to be true because you are assigning a non-zero value i.e, 1 and thus your function always returns 1. that's the reason why you get 100 1's as your answer.
So, instead try changing all the if conditions to something like:
if(n == 1)
{
//something...
}
This would check if n is equals to 1 or not. If n is equal to 1 then the if block is entered, else it would not enter the if block and the next if condition is checked.
Note: Just remember this while using the = and == operators
= is for assignment
== is for comparison
When you compare things in C++ you need to do it like:
if (a == b)
and not
if (a = b)
The latter will assign b to a and return the value of a.
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 6 years ago.
Improve this question
I'm trying to generate and print out 5 numbers from 1 to 5, but not in sequence. I'm using a self-written function, 'appearBefore' that will check whether the number has appeared before.
The function appearBefore will return '0' if the number has not appeared before, and '1' if the function has appeared before.
At the moment, the do-while loop doesn't get out of the loop even when 0 is returned. The program never ends. Any recommendations on what I can do?
EDITS - The downvotes sure comes fast. I have added the counter++, but it still does not work. Perhaps someone can advice on the inner-loop?
while (count < 5) {
repeat = 1;
do {
randomNumber = rand() % 4 + 1;
cout << randomNumber;
repeat = appearBefore(randomNumber);
cout << " " << repeat << endl;
} while (repeat == 1);
//Add the number into an array of numbers that have appeared before
checker[counterForChecker] = randomNumber;
counterForChecker++;
counter++;
}
This is the function appearBefore (the variables are global variables):
int appearBefore(int number) {
int x = 0;
int match = 0;
while (x < counterForChecker+1) {
if (checker[x] == number) {
match = 1;
break;
}
else {
match = 0;
}
x++;
}
return match;
}
You check for count < 5 while increasing counterForChecker.
Set the while condition to
while (counterForChecker < 5)
or increase the counter
counter++; // counterForChecker++;
(Assuming that counter++; actually says count++;...)
If x and k are positive, x % k is a number between 0 and k - 1.
So you have four possible values to choose from (1,2,3,4), and you're looping until you've found five unique values.
That will never end well.
To generate numbers from 1 to 5, use rand() % 5 + 1;
You'll want to change the variable count. This is now not done, so since the value does not change the loop will not end.
The loop is running while count < 5 and you never increment count.
Did you mean to use:
while (counterForChecker < 5)
If not, add:
++count;
at the end of the while loop
Use a debugger and step through the code, looking at the values of the variables as you do so. You'll learn more about how everything is working.