当前位置:嗨网首页>书籍在线阅读

21-求模运算符

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

3.4.3 求模运算符

比起求模运算符来说,多数人更熟悉加、减、乘、除,因此这里花些时间介绍这种运算符。求模运算符返回整数除法的余数。它与整数除法相结合,尤其适用于解决要求将一个量分成不同的整数单元的问题,例如将英寸转换为英尺和英分,或者将美元转换为元、角、分、厘。第2章的程序清单2.6将重量单位英石转换为磅。程序清单3.12则将磅转换为英石。记住,一英石等于14磅,多数英国浴室中的体重称都使用这种单位。该程序使用整数除法来计算合多少英石,再用求模运算符来计算余下多少磅。

程序清单3.12 modulus.cpp

// modulus.cpp -- uses % operator to convert lbs to stone
#include <iostream>
int main()
{
    using namespace std;
    const int Lbs_per_stn = 14;
    int lbs;
    cout << "Enter your weight in pounds: ";
    cin >> lbs;
    int stone = lbs / Lbs_per_stn;   // whole stone
    int pounds = lbs % Lbs_per_stn;  // remainder in pounds
    cout << lbs << " pounds are " << stone
         << " stone, " << pounds << " pound(s).\n";
    return 0;
}

下面是该程序的运行情况:

Enter your weight in pounds: 181
181 pounds are 12 stone, 13 pound(s).

在表达式lbs/Lbs_per_stn中,两个操作数的类型都是int,所以计算机执行整数除法。lbs的值为181,所以表达式的值为12。12和14的乘积是168,所以181与14相除的余数是13,这就是lbs % Lbs_per_stn的值。现在即使在感情上还没有适应英国的质量单位,但在技术上也做好了去英国旅游时解决质量单位转换问题的准备。