I am learning c++ currently and i have run to this problem:
Error Message: This Code should be of type bool or should be converted to bool.
The main function must stay the same, so i was wondering, that i use the line [A] and actuall return an bool.
The method should compare two cubics with each other, if they are the same or not the same.
Thanks in advance! :) <3
#include <iostream>
#include <cfloat>
class cubics
{
private:
double x,y,z;
bool var;
public:
cubics same(cubics cube)
{
double difference_x = x - cube.x;
double difference_y = y - cube.y;
double difference_z = z - cube.z;
if ( // If the difference between two objects are 0, then both cubics are the same; epsilon is used because we calculate with double floating precision to avoid the error)
(difference_x <= std::numeric_limits<double>::epsilon( )) and
(difference_y <= std::numeric_limits<double>::epsilon( )) and
(difference_z <= std::numeric_limits<double>::epsilon( ))
)
{
return (cube.var= true); // [A] I'm actually returning bool. But does the compiler want me to return the whole object!?
}
else
{
return (cube.var=false); // [A]
}
}
int main(){
cubics q2,q3;
cout << "The Cubics q2 and q3 are ";
if (q2.same(q3)) // <-- This line confuses me, however it must stay formally for my computerproject the same :) I understand that it means q2.same(q3) == true, but i don't know how i can return a boolean. I tryed [A]
cout << "same." << endl;
else
cout << "not same." << endl;
}
}
To return a boolean, you make the function… return a boolean.
Right now, it is trying to return an object of type cubics:
cubics same(cubics cube)
^^^^^^
Instead:
bool same(cubics cube)
^^^^
And return true, or return false, as appropriate.
That's it!
Your bool var doesn't need to exist at all.
I'd also recommend you take cube by reference; there's no need to take it by value, which makes a copy. So:
bool same(const cubics& cube)
Related
I'm creating an AI Director and need a way to change when the AI needs to pressure the player and when they need to move away. I've got a TArray of Objects and am checking the distance from the player. I'd like to either get the largest distance or the smallest distance.
I know this doesn't work:
operator comparer = PlayerTensionLevel > BackstageThreshold ? > : <;
Both of the variables used in the one line Bool are floats. I'm hoping that the comparer can be used in a situation like:
if(DistanceSquared(objectA, objectB) comparer _currentThresholdDistance){
_currentObject = objectA;
_currentThresholdDistance = DistanceSquared(objectA, objectB);
}
You can compute with bool! If you aren’t concerned with differing behavior for ties, you can just write
if((DistanceSquared(objectA, objectB) > _currentThresholdDistance) ==
(PlayerTensionLevel > BackstageThreshold)) …
(Technically, the extra parentheses here are unnecessary, but it’s probably not reasonable to expect the reader to know that relational operators have higher precedence than equality operators.)
As already mentioned in #SamVarshavchik's comment above,
You can use std::function and assign it to either std::less or std::greater based on PlayerTensionLevel and BackstageThreshold.
After you determine the comparator you can use it against the current values of _currentThresholdDistance and the the squared distance between the objects (here I just used dist2 to represent it).
#include <iostream>
#include <functional>
std::function<bool(float a, float b)>
GetComp(float PlayerTensionLevel, float BackstageThreshold)
{
if (PlayerTensionLevel > BackstageThreshold) {
return std::less<float>{};
}
return std::greater<float>{};
}
int main() {
float _currentThresholdDistance = 1;
float dist2 = 2;
float PlayerTensionLevel = 100;
float BackstageThreshold;
BackstageThreshold = 101;
std::cout << GetComp(PlayerTensionLevel, BackstageThreshold)
(dist2, _currentThresholdDistance) << std::endl;
BackstageThreshold = 99;
std::cout << GetComp(PlayerTensionLevel, BackstageThreshold)
(dist2, _currentThresholdDistance) << std::endl;
}
Output:
1
0
Not much else to add, in CodeAcademy's course they use the example of
int hunter = true;
int anger = true;
And I'm just confused, based on what I just googled it doesn't say anything about integer data types in C++ holding boolean values instead of, you know, what you'd classically think of as an integer.
Noob programmer so sorry if this is an obvious one.
true is casted to 1 and false is casted to 0
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
I am a beginner to c++ programming and I am given a task of implementation of fixed point math arithmetic in c++. here I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.
Test file
#include "fixed_point_header.h"
int main()
{
fp::fixed_point<long long int, 63> a=fp::fixed_point<long long int, 63>::positive_infinity(); // will assign positive infinity value to a from an function from header
fp::fixed_point<long long int, 63> b=fp::fixed_point<long long int, 63>::negative_infinity(); // will assign positive infinity value to b from an function from header
float nan=fp::fixed_point<long long int, 63>::isnan(a,b);
printf( "fixed point nan value == %f\n", float (nan));
}
In the header I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0.
Header file
#include fixed_point_header
static fp::fixed_point<FP, I, F> isnan (fp::fixed_point<FP, I, F> x,fp::fixed_point<FP, I, F> y){
/*if ( x + y ) happens, ie. x and y are infinities
{
should return 1; }
else {
should return 0; }
} */
can anyone please tell how to proceed with it? or how to solve this paradigm
I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.
That's simple enough; define a reserved value to represent nan (as you have for the infinities), and compare with that:
bool isnan(fixed_point x) {
return x == fixed_point::nan();
}
I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0
It would be the responsibility of the addition operator to check the inputs and return nan if appropriate:
fixed_point operator+(fixed_point x, fixed_point y) {
if (x == fixed_point::nan() || y == fixed_point::nan()) {
return nan;
}
if (x == fixed_point::positive_infinity()) {
return y == fixed_point::negative_infinity() ? fixed_point::nan() : x;
}
// and so on
}
then the test in main becomes:
bool nan = fixed_point::isnan(a+b);
Say I have a polynomial function f(x), and I want to use this expression into either the expression g(x) or h(x), depending on which the user chooses. Is this possible?
for example
int main() {
float fexpression = /* polynomial function f(x) here */;
/* some code where user picks g(x) or h(x) */
if (/* gexpression == true */)
cout << gfunction(fexpression);
else /* h expression == true */
cout << hfunction(fexpression);
return 0;
}
float gfunction(float j){
float var = /* some function representing g(f(x)) == g(j) */;
return var;
}
float hfunction(float j){
float var = /* some function representing h(f(x)) == h(j) */;
return var;
}
it just doesnt seem right to me that I can pass a variable that is an expression, such as
float fexpression = ....
You want a function pointer.
Make the expression a function.
float fexpression( float x )
{
return (5*(pow(x,4))) + (3*(pow(x, 3))) + (10 * x) - 5
}
This code, as you wrote it, will then pass the functionality itself.
if (/* gexpression == true */)
cout << gfunction(fexpression);
else /* h expression == true */
cout << hfunction(fexpression);
I tried to explain details of this in the comment section of Drew's answer, but it got lost in the formatting... so had to start another answer.
#DrewDorman's is right in saying you need to just define your expression as a function:
float fexpression( float x )
{
return (5*(pow(x,4))) + (3*(pow(x, 3))) + (10 * x) - 5
}
What is missing (for you) is the following (which you would get from reading Drew's link...):
define your gfunction as follows (for instance)
float gfunction(float (*funcp)(float)) {
// lots of stuff to determine the value of x
return (*funcp)(x);
}
This is how gfunction can evaluate your polynomial. Do something similar for hfunction
When you call gfunction, you have to reference fexpression as follows:
cout << gfunction(&fexpression);
the & matters... it was also missing from Drew's answer.
I have std::strings containing numbers in the leading section that I need to sort. The numbers can be integers or floats.
The vector<std::string> sort was not optimal, I found the following natural sort program which was much better. I still have a small issue with numbers smaller than zero that do not sort just right. Does anyone have a suggestion to improve? We're using Visual Studio 2003.
The complete program follows.
TIA,
Bert
#include <list>
#include <string>
#include <iostream>
using namespace std;
class MyData
{
public:
string m_str;
MyData(string str) {
m_str = str;
}
long field1() const
{
int second = m_str.find_last_of("-");
int first = m_str.find_last_of("-", second-1);
return atol(m_str.substr(first+1, second-first-1).c_str());
}
long field2() const
{
return atol(m_str.substr(m_str.find_last_of("-")+1).c_str());
}
bool operator < (const MyData& rhs)
{
if (field1() < rhs.field1()) {
return true;
} else if (field1() > rhs.field1()) {
return false;
} else {
return field2() < rhs.field2();
}
}
};
int main()
{
// Create list
list<MyData> mylist;
mylist.push_front(MyData("93.33"));
mylist.push_front(MyData("0.18"));
mylist.push_front(MyData("485"));
mylist.push_front(MyData("7601"));
mylist.push_front(MyData("1001"));
mylist.push_front(MyData("0.26"));
mylist.push_front(MyData("0.26"));
// Sort the list
mylist.sort();
// Dump the list to check the result
for (list<MyData>::const_iterator elem = mylist.begin(); elem != mylist.end(); ++elem)
{
cout << (*elem).m_str << endl;
}
return 1;
}
GOT:
0.26
0.26
0.18
93.33
485
1001
7601
EXPECTED:
0.18
0.26
0.26
93.33
485
1001
7601
Use atof() instead of atol() to have the comparison take the fractional part of the number into account. You will also need to change the return types to doubles.
If it's just float strings, I'd rather suggest to create a table with two columns (first row contains the original string, second row is filled with the string converted to float), sort this by the float column and then output/use the sorted string column.
If the data are all numbers I would create a new class to contain the data.
It can have a string to include the data but then allows you to have better methods to model behaviour - in this case espacially to implement operator <
The implementation could also include use of a library that calculates to exact precion e.g. GNU multiple precision this would do the comparison and canversion from string (or if the numbers do not have that many significant figures you could use doubles)
I would compute the values once and store them.
Because they are not actually part of the objects state (they are just calcualted values) mark them as mutable. Then they can also be set during const methods.
Also note that MyClass is a friend of itself and thus can access the private members of another object of the same class. So there is no need for the extranious accessor methods. Remember Accessor methods are to protect other classes from changes in the implementation not the class you are implementing.
The problem with ordering is that atoi() is only reading the integer (ie it stops at the '.' character. Thus all your numbers smaller than 0 have a zero value for comparison and thus they will appear in a random order. To compare against the full value you need to extract them as a floating point value (double).
class MyData
{
private:
mutable bool gotPos;
mutable double f1;
mutable double f2;
public:
/*
* Why is this public?
*/
std::string m_str;
MyData(std::string str)
:gotPos(false)
,m_str(str) // Use initializer list
{
// If you are always going to build f1,f2 then call BuildPos()
// here and then you don't need the test in the operator <
}
bool operator < (const MyData& rhs)
{
if (!gotPos)
{ buildPos();
}
if (!rhs.gotPos)
{ rhs.buildPos();
}
if (f1 < rhs.f1) return true;
if (f1 > rhs.f1) return false;
return f2 < rhs.f2;
}
private:
void buildPos() const
{
int second = m_str.find_last_of("-");
int first = m_str.find_last_of("-", second-1);
// Use boost lexical cast as it handles doubles
// As well as integers.
f1 = boost::lexical_cast<double>(m_str.substr(first + 1, second-first - 1));
f2 = boost::lexical_cast<double>(m_str.substr(second + 1));
gotPos = true;
}
};