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」のように 10 進値がないため、どちらが意図したとおりに機能しませんか?

しかし、すべての値を「double」型に変更すると、% は「double」では機能しません。これを簡単にする方法はありますか?fmod() について聞いたことがありますが、CodeBlock IDE は fmod() を認識しないようです?

また、「float」を試してみましたが、「float」でも % が機能しないようです。では、% が使用できる変数の型は何ですか? そして、このリファレンスはどこにありますか?

4

2 に答える 2

2

std::fmodC から継承された を見てください。

于 2013-09-28T11:46:46.343 に答える
1

すべてを double として宣言するだけで、キャストする必要はありません。

フィート数は連続量であるため、double を使用する方が理にかなっています。

次のように式をキャストすることもできます。

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