我想我理解这一点。但有没有办法让这更简单?

时间:2013-09-28 10:41:22

标签: c++

我是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()?

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

2 个答案:

答案 0 :(得分:2)

查看继承自C的std::fmod

答案 1 :(得分:1)

只需将所有内容声明为双,然后就不需要施放。

使用double更有意义,因为脚数是连续数量。

您也可以在表达式中投射:

int daysperweek = 7;
double val = daysperweek * 52.0;  // using 52.0 will use implicit conversion