c++cmath

How to use cmath functions like div in C++?


I am new to C++ and I am not sure how to use some of the cmath functions like div.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n;
    cin >> n;

    if (n < 10) {
        cout << div(n , 2);
    }

    return 0;
}

Solution

  • The reason cout << div(n , 2) doesn't work is because div doesn't return a number, instead div returns a struct with 2 values in there, quot and rem.

    So when you use div(10, 3), it will returns a object with .quot == 3 and .rem == 1.

    To print the result of div, you would need to first store the result, then print each members separately:

    auto result = std::div(10, 3);
    std::cout << "Quot: " << result.quot << '\n';
    std::cout << "Rem: " << result.rem << '\n';