0

Modulo issue C++

Hi all, why is it not possible to use code like this? (All integers) ... cin >> number; cin >> i; cout << number % pow(10,i); ... This returns a bunch of errors depending on compiler, something about mismatch int, double, bool.... but I use only integers... I must declare new variable first and fill it with divisor like: x = pow(10,i); cout << number % x; This works but why can't I use it directly? I have only 16GB RAM and need to save every integer declared :-) Thanks

2nd Dec 2020, 11:26 AM
Jiří Ťápal
Jiří Ťápal - avatar
2 Antworten
+ 4
You can't use it directly like that because std::pow() always returns a floating point type, not an integral type: https://en.cppreference.com/w/cpp/numeric/math/pow However, the built-in remainder operator requires both operands to be integral types. An explicit cast would do the job, i.e. number % static_cast< int >( pow( 10, i ) ); or in C-style: number % ( int ) pow( 10, i ); When assigning the return value to an integer variable, this conversion is done implicitely. But I don't see why you would have to worry about one integer with 16GB of RAM (I'd tend to think the compiler would potentially optimize it away anyway).
2nd Dec 2020, 12:43 PM
Shadow
Shadow - avatar
0
Thank you Shadow. Now it is clear. Regarding the RAM, I tried to joke a little. Never mind...
2nd Dec 2020, 2:04 PM
Jiří Ťápal
Jiří Ťápal - avatar