-1

While working on a fairly large project, I happened to notice that one of my functions that is supposed to return a Long value is either returning an Integer. I reproduced the error in a very small environment thinking that it would make the problem clear to me, but I'm still not seeing the issue. The input is 1.123, and the return value is 1. If I input any Long, for example; 123.456, it will only return 123. What am I not seeing?

Source1.cpp

#ifndef HEADER_H
#define HEADER_H


using namespace std;

class testClass
{

private:
    long m_testLong = 0.0;

public:

    long getTestLong();
    void setTestLong(long sn);
};

#endif

Header.h

#include "Source1.cpp"
#include <string.h>

void testClass::setTestLong(long sn)
{
    m_testLong = sn;
}

long testClass::getTestLong()
{
    return m_testLong;
}

Source.cpp

#include <iostream>
#include "Source1.cpp"
#include "Header.h"

using namespace std;

int main(void)
{

testClass *myClass = new testClass;

cout << "Setting test long value using setTestLong function -- 1.123" << endl;
myClass->setTestLong(1.123);
long tempTestLong = 0.0;
tempTestLong = myClass->getTestLong();
cout << tempTestLong << endl;

system("Pause");
return 0;
}

OK, so the answer was painfully simple. I hadn't worked with longs before, but I thought I knew what they were. I didn't.

So longs and integers both are whole numbers, and having the type listed as long made me assume an integer wouldn't work, and I tested the function with a double because of my misunderstanding. Thanks for the help!

3
  • You should have read basic documentation on the language you're trying to use: en.cppreference.com/w/cpp/language/types
    – ach
    Sep 24, 2014 at 4:08
  • Yeah, I made a quick assumption that was incorrect. I'll read the full C++ documentation next time I find an error. Sep 24, 2014 at 4:09
  • nobody expect you to read full C++ documentation, but what you're asking about is the ABC.
    – ach
    Sep 24, 2014 at 5:58

2 Answers 2

2

The long and int types are integral types, they can only hold whole numbers like 7 or 42.

You should be using float or double as a type, preferably the latter for increased range and precision. That will allow you to hold real numbers such as 3.141592653589 or 2.718281828459.

1

Long is an integer. Assigning a floating point value to integer causes rounding.

You want double or float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.