MyNameIsKhan
MyNameIsKhan

Reputation: 2612

Visual Studio not letting me use sqrt or floor, ambiguous call to overloaded function

I have a call to

long long a = sqrt(n/2);

Both a and n are long long's but it won't let me compile because it says my use of sqrt() is an ambiguous call. I don't see how it's possibly ambiguous here at all. How do I resolve this? I have the same problem with floor().

My includes

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

Upvotes: 6

Views: 6426

Answers (4)

//use 
sqrt(static_cast<double>(n/2));
//instead of 
sqrt(n/2);

Upvotes: 6

stefan bachert
stefan bachert

Reputation: 9616

According to the reference

http://www.cplusplus.com/reference/clibrary/cmath/sqrt/

I would propose to convert to long double first. No overload of sqrt accepts an integral value

integral parameter could always result in a "real" value (float, double, long double)

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263220

The sqrt functions expects a float, a double or a long double:

long long a = sqrt(n * 0.5);

You may lose some precision converting a long long to a double, but the value will be very close.

Upvotes: 3

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81704

There are several overloads of sqrt() and floor(), there's no "best match" for a call to sqrt(long long) according to the overload resolution rules. Just cast the argument to the appropriate type -- i.e.,

long long a = sqrt(static_cast<double>(n/2));

Upvotes: 8

Related Questions