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
Getting Douglas Adams vibes here...
I just started out with c++ and doing some code challenges right now.
The current challenge is to create a function that takes a number as its only argument and returns true if it's less than or equal to zero, otherwise return false.
However, when I run the program I get the number 42??
I actually don't need help for the challenge itself, I just wonder if someone could explain why I get this result :)
#include <iostream>
#include <string>
using namespace std;
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
}
int main()
{
cout << lessThanOrEqualToZero(5);
}
The function bool lessThanOrEqualToZero(int);, as defined, makes your program have undefined behavior since not all paths in the function leads to the function returning a bool that you declared that it should return. Specifically: If num > 0 is true the function doesn't return a value.
When a program has undefined behavior, you can't trust anything it does. Your program could therefore print just about anything or nothing, crash or do something completely wild.
In some compilator implementations, a value could be picked from the stack where it expects to find the promised bool and then print whatever that value was (42 in your case). The stack will then be corrupt. Other implementations may compile it into a program that does something completely different. You'll never know.
The solution is to make sure that all paths leads to a return:
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
return false;
}
This however better written as:
bool lessThanOrEqualToZero(int num)
{
return num <= 0;
}
otherwise return false
Well then you do need to return false otherwise.
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
I'm working on this function for one of my classes and my pass count works just fine, however, my fail count ALWAYS prints out 12. I've been reading my code top to bottom and just can't seem to find the problem.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string passAndFailCount(string grades){
int pass_count;
int fail_count;
istringstream myStream(grades);
string grade;
while(myStream>>grade){
int i_grade=stoi(grade);
if (i_grade>=55){
++pass_count;
}
else{
++fail_count;
}
}
cout<<"Pass: "<<pass_count<<endl<<"Fail: "<<fail_count<<endl;
}
int main()
{
string grades;
getline(cin, grades);
passAndFailCount(grades);
}
Your problem are uninitialized variables.
int pass_count = 0;
int fail_count = 0;
and you're set.
For an explanation. Non-global variables (which automatically get initialized to 'default' (0) as per the standard), automatic and dynamic variables (like the one you are using), assume the value of 'whatever was in memory at the time of allocating the variable'.
Memory is never empty, there's always 'something' written in there.
So the memory of your fail_count variable just 'happened to be' 12 during allocation, which is why you start with that value. This value can be anything within scope.
By explicitly assigning a variable, you 'initialize' the variable, putting it into a defined state (0) and your program should start working as expected.
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'm playing around with the Sleep() function in C++ right now, and I am not understanding why this code operates the way it does.
I made a program to find the difference between two times, but it is not working as expected.
#include <iostream>
#include <chrono>
#include <Windows.h>
using namespace std;
int main() {
int timeA = (int)chrono::system_clock::now;
cout << timeA << "\n";
for (int i = 0; i < 5; i++) Sleep(1000);
int timeB = (int)chrono::system_clock::now;
cout << timeB << "\n";
int timeDifference = timeB - timeA;
cout << timeDifference;
cin.get();
return 0;
}
It seems as if the program is setting the variables at the same time, and then sleeping. Is this the case? If so, help me to understand why, please.
now is a function, not an attribute or variable. You failed to call it, and are casting the function pointer itself to int, which will always produce the same value for a given run (on a typical 64 bit system, the low 32 bits of the address where now is located).
Change both lines to use chrono::system_clock::now(), not chrono::system_clock::now.
Note that this is one of the reasons to avoid C-style casts, as well as a reason to compile with warnings turned up; it protects you from casting to wildly incorrect end results, without at least some sort of alert.
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 5 years ago.
Improve this question
I made this function that returns the number of digits in an integer:
it works fine when I used ELSE to return the count
int getIndex(int number, int count) { // at first call count is 0
number /= 10;
if (number > 0){
getIndex(number,++count);
}
else{
return ++count;
}
}
but when I first tried to execute without ELSE statement I thought function will be called recursively till IF condition is not met and then only it will encounter the return statement
And function will exit there as integer is returned, but
actually
if the number contains more than one digit, doesn't matter how many time it increase with recursive call it outputs 2
Just curious where as to why I am getting my concept wrong
it works fine when I used ELSE
Actually, the behaviour of the shown program is undefined. If the if branch is entered, then no return statement will be reached, and the behaviour of the program will be undefined.
When you remove the else statement and instead return unconditionally, the behaviour is well defined: The function will always return count + 1 or count + 2 depending on the value of number (which isn't correct).
Consider this, where do you use the value of the recursive function call? Nowhere; you simply discard the value. Would it make sense to return that value to the caller? Yes, it would. If only you returned within the if branch, the behaviour would be correct.
return getIndex(number,++count);
Then it won't matter whether the recursion-terminating branch is within else or not, it will only be executed if the if branch is not executed:
You are missing a return before the recursive call.
By default, it returns 0 (for some compilers).
Edit:
But actually the code should have looked like this:
int getIndex(int number) {
if (number > 0) {
return getIndex(number/10) + 1;
} else {
return 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 4 years ago.
Improve this question
Having issues with my code... the program compiles, but then it gives the following statement "Run-Time Check Failure #3 - The variable 'result' is being used without being initialized." It then ends the program at that point. Everything I have after trying to run the function is ignored. What should I do?
double result;
for (int i=0; i<nRows; i++)
{
absum.push_back(vector<double>());
for (int j=0; j<nColumns; j++)
{
double temp;
temp = matrixa[i][j]+matrixb[i][j];
absum[i].push_back(temp);
cout << temp << '\t';
}
cout << endl;
}
return result;
At the top of your code you have:
double result;
At the moment it's not initialised to anything at all, so the compiler won't use it. So you need to need to initialise it thus:
double result = 0;
It's also generally good practice to initialise every variable you use in C++, that way you don't get nasty compiler messages, and don't run the risk of returning some random chunk of memory. You always want to start your program from a known state, so if you know that result is 0, then all is good.
C++ is picky about this sometimes, have you tried double result = 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 1 year ago.
Improve this question
This is a function to check a number for a power of two. Although the compiler does not print anything, it's also not showing any errors. Please let me know if the logic is correct or not.
Here is my code:
#include <bits/stdc++.h>
using namespace std;
bool isPowerofTwo(long long n)
{
// Your code here
for (int i = 1; i <=n; i<<1)
{
if(i==n){
return true;
}
}
return false;
}
int main()
{
cout << isPowerofTwo(2);
return 0;
}
The expression i<<1 in the third statement (the "iteration expression") of your for loop doesn't actually do anything (that is, it doesn't modify the value of i). You need, instead, i<<=1 (or, in 'long form', i = i << 1).
Also, please read: Why should I not #include <bits/stdc++.h>?. In your code, the only standard header you need is #include <iostream>. Another good post to read is: Why is "using namespace std;" considered bad practice?.