c++如何使用模数

C++ how to use modulus

本文关键字:何使用 c++      更新时间:2023-10-16
#include<iostream>
using namespace std;
int main()
{
    int ID,year;
    cout<<"Enter your ID";
    cin>>ID;
    year=
      cout<<"Year="<<year;

    system("pause");
}

cin示例(20132724,20115555)

我的问题是我如何能使Year采取前4个数字(从左)从ID

为什么要使用模数运算符?

你应该把你的int变成一个字符串,取前4个字符,然后把结果字符串变成一个int

int ID_only = ID % 10000;  //ID only can be extracted like this
year = ID / 10000;        //this will get integer result not fraction 

假设:您的ID将只有8位数字

像这样考虑模数——它返回除法的余数。在您的示例中,例如20132724。如果你把这个数除以10000,你会得到2013.2724对它取余就是周期之后的数。

我将以这种方式提取前四个数字-因为它已经是int型了。

#include<iostream>
int main()
{
    int ID, year;
    ID = 20132724;
    year = ID / 10000;
    std::cout << "Year = " << year; // since the type is int it 
                                    //wont print the fraction part
    return 0;
}