Modf is not a member of std in C++

Modf is not a member of std in C++

 2 minute read

IntroductionPermalink

The std::modf function is a function that allows us to break down the floating-point into a whole and fractional part. However, we can often get errors from the compiler such as:

error: ‘modf’ is not a member of ‘std’

This error is pretty straight-forward to fix as we will see below.

Potential causesPermalink

This error could be caused by multiple reasons.

Fix #1: Add iostream to your depedenciesPermalink

Essentially, the std::modf function needs to have access to the cmath module in order to be executed by the compiler.

Therefore, you must add the following #include header to the top of your code (in the include(s) part) such as:


#include <cmath> //Add this

int main() {
    float myFloat = 21.41;
    float wholePart, fractionalPart;
    fractionalPart = std::modf(myFloat, &wholePart);
    return 0;
}

The compiler should now recognize the std::modf function and you should not get the error anymore. If you still get the error, then continue reading below.

Fix #2: Using namespace stdPermalink

Note that we have previously typed: std::modf instead of modf. We can type “modf” only if we are declaring that we are using its namespace.

In other words, we would need to type “using namespace std” in the header if we only want to type modf (which is obviously shorter) instead of std::modf. For instance, we can have something like:


#include <cmath>
using namespace std; //Add this
在Qt中 std已经放入全局空间,直接用modf int main() { float myFloat = 21.41; float wholePart, fractionalPart; fractionalPart = modf(myFloat, &wholePart); return 0; }

It is okay to type std::cout without typing “using namespace std”. In fact, it is generally recommended to type the full std::modf function name (and therefore avoiding using namespace std) when working with multiple libraries because it can reduce future confusion.

However, if you still want to type “modf” instead of “std::modf”, then you need to add “using namespace std” to the header

posted on 2022-10-29 22:53  zxddesk  阅读(45)  评论(0编辑  收藏  举报

导航