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.
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 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.
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'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.
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 6 years ago.
Improve this question
#include<iostream>
using namespace std;
int factorial(int x)
{
if(x == 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
int main()
{
cout<<factorial(5)<<endl;
}
I don’t get the part when the value reaches 1. Why doesn't the program print 1 as the output, because when 1 is reached it returns 1. Consider the below steps.
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So now, when the x value becomes 1 and goes into if , condition becomes true and 1 is returned. So why doesn't it output 1? Is it that the value of the 5*4*3*2*factorial(1) is stored somewhere and the returned value of just gets multiplied with 5*4*3*2*1 and outputs 120?
Also please explain, what happens when we pass 0 instead of 5,how will it output 1? (0!=1)
it is exactly like you said:
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So if it reaches 1 then this will be replaced by
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*1
so the result of the last step goes into the second last step.... where 2*1 will be calculated... After that the 3rd last step gets the value of 2*1 = 2 and multiplies 3 on in and so on.
If you insert smaller or equal 0 into your function, you will get an endless recursion because if(0 == 1). But if you replace this code with
int factorial(int x)
{
if(x <= 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
Then also 0 and -numbers will work
The stack stores in some sense all pending operations. As soon as fact(2) gets 1 from the call, it multiplies it by 2 and returns 2. fact(3) receives that 2, multiplies it by 3 and returns 6. fact(4) receives that 6, multiplies it by 4 and returns 24. And so on...
Passing a 0 was not thought of in the current form of the program and will actually cause the program to crash (most likely). Changing the if(x==1) line to if(x==0) will fix this.