How to find year using mod function?

Viewed 50

I want to know the mod function. It's like we've been searching for years after using the mod function in Excel. Can we do the same in c++?

For example, when mod in Excel, Id = 199734902138 = mod(id,100000000) As the answer, 34902138 Then id - 34902138 As the answer, 199700000000 Then 199700000000/100000000 Then we can get as the answer 1997 This is the year 1997

How to do the same thing in c++ using mod as mentioned above? I want to know that. Can you please help with that?

2 Answers

In C++, % is modulo operator, like

long int ID = 199734902138;
long int m = ID % 100000000; // results 34902138
int year = (ID - m) / 100000000; // results 1977

But a simple division does the same thing in C++, because an integer divided by an integer results another integer

int year = 199734902138 / 100000000; // results 1977

Modulo doesn't find year, it returns the remainder after a division.

The modulo operator is %.

For example:

#include <iostream>

int main() {

    int x;
    x = 10 % 8; 

    std::cout << x << std::endl; // output is 2
    return 0;
}

Given your example, the following code would perform the same order of operations as your question. Notice the use of the long long int data type. Values this high (12-digit numbers) can only be expressed using long long int type.

#include <iostream>

int main() {

// declare variable id = 199734902138 and initial answer
long long int id = 199734902138;
long long int answer = id % 100000000;

// answer is now 199700000000 
answer = id - answer;

//final calculation, divide the answer by 100000000
id = answer / 100000000;

// output id for verification 
std::cout << id <<std::endl;

return 0;

}

As mentioned, this is all a bit superfluous as a simple divide operation will yield the same result, however if these steps need to be explicitly used in your calculation, then the code above would fit.

Related