0

I am writing a project in Visual Studio then I use GCC in order to compile it. Sometimes it causes some problems: This time I cannot use sqrtf function because VS accepts it however GCC does not. So I need to find some way (maybe mathematical approach to calculate square root) to find square root of some number in a way both GCC and VS will accept. To be more precise this is the line which causes a problem:

float x_f = circleRadius - sqrtf((float)((circleRadius * circleRadius) - (y * y)));

I need to find the square root of (circleRadius^2 - y^2)

  • 2
    `To be more precise this is the line which causes a problem` which one? Linker error? Syntax error? – emacs drives me nuts Jan 24 '20 at 09:28
  • 2
    Have you tried std::sqrt? https://en.cppreference.com/w/cpp/numeric/math/sqrt – Stefan Groth Jan 24 '20 at 09:29
  • 2
    Please provide details. `sqrtf` is definitely provided by all compilers. – Acorn Jan 24 '20 at 09:33
  • Please provide a [repro] of the issue. `sqrtf` is certainly available, at least since C++11. Also note that the explicit cast is redundant. `std::sqrtf` already casts the argument to `float` implicitly. – walnut Jan 24 '20 at 09:50

2 Answers2

3

std::sqrt solves this problem:

#include <cmath>

auto foo(int circleRadius, int y) {
    float x_f = circleRadius - std::sqrt((float)(circleRadius * circleRadius - y * y));
}

compiles for both msvc and gcc according to https://godbolt.org/z/g9MJH6

You should prefer std::sqrt to sqrtf in C++. It works with more types, i.e., you could write your function more generically. It also does not use hungarian notation.

Edit: If you do not care if the calculation returns a float or a double, you could omit the cast and write the following:

auto x_f = circleRadius - std::sqrt(circleRadius * circleRadius - y * y);

If you care that a float is used, you can use std::sqrtf instead. If you have to use a cast, you should generally prefer static_cast to C-style casts. Reasons for this are listed here.

Stefan Groth
  • 154
  • 7
  • 3
    Note though that this would work with `std::sqrtf` just as well. OP's error lies probably in using wrong includes, forgetting the `std::` prefix or compiling against pre-C++11. – walnut Jan 24 '20 at 09:47
0

Your situation may be if you use newer compiler at VC and older compiler at gcc.

Try to use sqrt or sqrtf WITH

#include <math.h>

Don't use

#include <cmath>

math.h should have sqrt, sqrtf definitions for both compilers.

Evgeny
  • 1,072
  • 6
  • 6
  • 2
    I don't think that is a good suggestion. Rather, I would suggest always using `#include` and using `std::sqrtf` instead. That would be much more consistent with the rest of the standard library. – walnut Jan 24 '20 at 09:42