I think I understand this. But is there a way to make this simpler?
I'm a beginner in C++ and I came across this code:
#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;
}
It works as you expect but I didn't like all the typecasting business. So
I changed this to this:
#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;
}
Which of course does not work as intended because 'long' doesn't have
decimal values like 'double' does, right?
But if I change every value to the type 'double', then % does not work
with 'double'. Is there a way to make this easier? I heard about fmod()
but CodeBlock IDE doesn't seem to recognize fmod()?
No comments:
Post a Comment