0

我是 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”那样的十进制值,对吧?

但是,如果我将每个值都更改为“double”类型,则 % 不适用于“double”。有没有办法让这更容易?我听说过 fmod() 但 CodeBlock IDE 似乎无法识别 fmod()?

另外,我尝试了“float”,似乎 % 也不适用于“float”。那么 % 使用的变量类型是什么?我在哪里可以找到这个参考?

4

2 回答 2

2

std::fmod,它继承自 C。

于 2013-09-28T11:46:46.343 回答
1

只需将所有内容声明为双重,然后您就不需要投射。

使用 double 更有意义,因为英尺数是一个连续的数量。

您还可以将表达式转换为:

int daysperweek = 7;
double val = daysperweek * 52.0;  // using 52.0 will use implicit conversion
于 2013-09-28T13:18:25.860 回答