我想我明白这一点.但是有没有办法使这更简单
I think I understand this. But is there a way to make this simpler?
我是C++的初学者,我遇到了这段代码:
#include <iostream>
using namespace std;
int main()
{
const long feet_per_yard = 3;
const long inches_per_foot = 12;
double yards = 0.0; // Length as decimal yards
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards, feet and inches
yds = static_cast<long>(yards);
ft = static_cast<long>((yards - yds) * feet_per_yard);
ins = static_cast<long>(yards * feet_per_yard * inches_per_foot) % inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches.";
cout << endl;
return 0;
}
它按您的预期工作,但我不喜欢所有的类型转换业务。所以我把它改成这样:
#include <iostream>
using namespace std;
int main()
{
long feet_per_yard = 3;
long inches_per_foot = 12;
long yards = 0.0;
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards, feet and inches
yds = yards;
ft = (yards - yds) * feet_per_yard;
ins = (yards * feet_per_yard * inches_per_foot) % inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches.";
cout << endl;
return 0;
}
这当然不能按预期工作,因为"long"不像"double"那样具有十进制值,对吧?
但是,如果我将每个值都更改为"双精度"类型,则%不适用于"双精度"。有没有办法让这更容易?我听说过 fmod(),但 CodeBlock IDE 似乎无法识别 fmod()?
另外,我尝试了"浮点",似乎%也不适用于"浮点"。那么%,%可以使用哪些类型的变量呢?我在哪里可以找到这个参考?
看 std::fmod
,它是从 C 继承而来的。
只需将所有内容声明为 double,然后就不需要投射了。
使用双倍更有意义,因为英尺数是一个连续的数量。
您还可以在表达式中强制转换,如下所示:
int daysperweek = 7;
double val = daysperweek * 52.0; // using 52.0 will use implicit conversion
相关文章:
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- 有没有办法在 c++ 中按更大的 int 和更小的对对 int 和对的集合进行排序?
- 在 C++11 及更高版本中,有没有办法初始化初始值设定项列表中的向量?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 有没有更好的方法对C++中的三个整数进行排序?
- 有没有比static_cast更优雅的从int到float的演员阵容<float>?
- VisualC++ 2010 有没有办法找出有关未处理异常错误的更多详细信息
- 有没有简单的方法可以将"02:00"转换为分钟,比如 120?
- 有没有更快的方法可以在 std::vector 中插入元素
- 有没有办法使这段代码更快?
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 有没有更简单的方法可以从用户那里获取三个数字并按升序打印它们?
- 有没有一种方法可以在基于枚举的可变参数模板函数之间进行选择,这比将函数包装在结构中更简单
- 有没有更简单的方法可以做到:if(num1 > num2 && num1 > num3),以获得更大的变量列表进行比较?
- 有没有更简单的方法在 Rcpp 中使用 NumericVector 编写条件语句
- 我想我明白这一点.但是有没有办法使这更简单
- 有没有一种更简单的方法可以像在java中使用包一样在C++中重用代码?制作头文件比较复杂
- 有没有一种更简单的方法来实例化静态库