一种简化求余数的方法

A way to simplify getting a remainder

本文关键字:余数 方法 一种      更新时间:2023-10-16

对不起,我找不到更好的方式来表达这个问题。无论如何,我没有任何错误,但我想知道是否有一种方法可以简化它:

#include <iostream>
int main(void)
{
    const int Lbs_per_stone = 14;
    int lbs;
    std::cout << "Enter your weight in pounds: ";
    std::cin >> lbs;
    int stone = lbs / Lbs_per_stone; // whole stone
    int pounds = lbs % Lbs_per_stone; // remainder in pounds
    std::cout << lbs << " pounds are " << stone << " stone, " << pounds << " 
    pound(s)." << std::endl;
    std::cin.get();
    std::cin.get();
    return 0;
}

到这里,我不必声明两个单独的整数来输出以斯通为单位的数字和以磅为单位的余数。有没有更好的方法可以做到这一点?

了解在<cstdlib>中声明的std::div

如果这让你感到困扰,你可以做几件事:

使用类

template <typename T>
struct Div_Mod
{
    Div_Mod(T a, T b) : div(a/b), mod(a % b) { }
    T div, mod;
};
Div_Mod<int> weight(lbs, LBS_PER_STONE);
std::cout << weight.div << ' ' << weight.mod << 'n';

确保最佳机器代码

如果你为自己正在进行机器代码操作以获得/%的每个结果而烦恼,那么你可能不应该这样做——你的优化器应该处理好这一点,但如果你坚持要确定你可以使用Pete Becker建议的std::div等人,他们可能会使用这种优化,但如果它没有,那么就寻找编译器或操作系统提供的内部程序,或者使用CPU特定的内联程序集来执行类似的指令http://x86.renejeschke.de/html/file_module_x86_id_137.html

如果您不想将它们存储在变量中,那么不要:

int main()
{
    const int LBS_PER_STONE = 14;
    int lbs;
    std::cout << "Enter weight in pounds:  ";
    std::cin >> lbs;
    std::cout << "Your weight is " << (lbs / LBS_PER_STONE) << " and " << (lbs % LBS_PER_STONE) << " pounds" << std::endl;
    return 0;
}

你的意思不是显而易见的,比如:

std::cout<lt;磅<lt;"磅"<lt;(lbs/lbs_per_stone)<lt;"石头"answers"<lt;(lbs%lbs_per_stone)<lt;磅。"<<std::endl;

保存int的唯一其他方法(不使用临时值)是从lbs中扣除石头:

std::cout<lt;磅<lt;"英镑是";int stone=lbs/lbs_per_stone;lbs-=石头*lbs_per_stone;std::cout<lt;石头<lt;"石头"answers"<lt;磅<lt;磅。"<<std::endl;

希望这能帮助