我想我明白这一点.但是有没有办法使这更简单

I think I understand this. But is there a way to make this simpler?

本文关键字:更简单 有没有 我明白 这一点      更新时间:2023-10-16

我是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
相关文章: