-3

I wrote a program which takes an integer k and calculates geometric sum till 2^k.


using namespace std;



long double recursive( long double n){
    if(n==1){
        return 1;
    }
    long double ans = recursive(2*n);
    return n+ans;
}

int main() {
    int k;
    cin>>k;
    
    int n = 1<<k;
    long double d = 1/long double(n);
    
    cout<<recursive(d)<<endl;
    
    return 0;
}

Here while converting n(integer) to long double

   long double d = 1.0/long double(n);

I'm getting the following error

error: expected primary-expression before ‘long’   
 long double d = 1.0/long double(n);     
                         ^~~~

Whereas when I declare

double d = 1.0/double(n);

The program runs without any error. Why do I get error when I declare as long double?

I know I can make n as long double while declaring itself, but I wanted to know the reason for this error and how to solve this .

dL1ght
  • 3
  • 2

2 Answers2

0
long double d = 1.0 / long double(n); // functional-cast, not works
long double d = 1.0 / (long double)n; // C-style cast, works here.
  1. The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses. This cast expression is exactly equivalent to the corresponding C-style cast expression.

from here, which means only one word is valid since it is deemed as a function name.

Nimrod
  • 1,150
  • 7
  • 17
0

This is something inherited from C. While doing the code analysis, the compiler sees "long" and "double" as two separate words. The same would occur for something like "unsigned int".

There are multiple ways to achieve what you want. In C you would cast it

long double my_var = 1/(long double)4;

C++ supports this because of legacy compatibility, but it's not compile time checked.

C also provides floating point literals, that are also in C++

long double my_var = 1/4.0L;

In C++ you could make your own alias to the double word type with a using statement

using LongDouble = long double;

auto my_var{1/LongDouble{4}};

But the preferred C++ way is to use static_cast

auto my_var{1/static_cast<long double>(4)};
JHBonarius
  • 8,837
  • 3
  • 16
  • 32
  • Now I understood , thanks. Will Use static cast from next time – dL1ght Jan 07 '22 at 11:13
  • @dL1ght you're welcome. In C++ we try to be type strict and use explicit conversions. There have been real-world serious issues caused by types not being what you expect. E.g. overflow errors. – JHBonarius Jan 07 '22 at 11:38
  • Hmm, I'll keep that in mind, Thanks @JHBonarius – dL1ght Jan 10 '22 at 12:48