一种简化求余数的方法
A way to simplify getting a remainder
对不起,我找不到更好的方式来表达这个问题。无论如何,我没有任何错误,但我想知道是否有一种方法可以简化它:
#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;
希望这能帮助
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 计算浮点余数的最佳方法
- 一种简化求余数的方法
- 提取整数余数的最佳方法
- 最好的方法来获得整数除法和余数