如何使用mod函数查找年份



我想知道mod函数。这就像我们在Excel中使用mod函数后已经搜索了很多年。我们能在c++中做同样的事情吗?

例如在Excel中进行mod时,Id=199734902138=mod(id,100000000(作为答案,34902138然后id-34902138作为答案,1997000000001997年那么我们可以得到1997年的答案这是1997年

如何在c++中使用如上所述的mod做同样的事情?我想知道。你能帮忙吗?

在C++中,%是模运算符,与类似

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

但在C++中,简单的除法也能起到同样的作用,因为一个整数除以一个整数会得到另一个整数

int year = 199734902138 / 100000000; // results 1977

Modulo找不到年份,它返回除法后的余数。

模运算符是%

例如:

#include <iostream>
int main() {
int x;
x = 10 % 8; 
std::cout << x << std::endl; // output is 2
return 0;
}

在您的示例中,以下代码将执行与您的问题相同的操作顺序。请注意long-long-int数据类型的使用。如此高的值(12位数字(只能使用long-long-int类型表示。

#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;
}

如前所述,这一切都有点多余,因为简单的除法运算会产生相同的结果,但是,如果这些步骤需要在计算中明确使用,那么上面的代码就适合了。

最新更新