Write compare_ratios2.cpp to take four nonnegative integers a, b, c and d (in th
ID: 3620125 • Letter: W
Question
Write compare_ratios2.cpp to take four nonnegative integers a, b, cand d (in that order) on std :: cin and to judge whether a/b or c/d is
the larger, using only integral arithmetic. Requirements:
• Let the program use a function int compare( int, int, int, int ) to
do the actual judging, where compare() returns -1 if c/d is the
larger, 1 if a/b is the larger, and 0 if the two are equal.
• Let your main() itself handle input and output, but little or nothing
else. Output should resemble
The ratio 35/61 is the larger.
The ratio 4/7 is the larger.
The two ratios are equal.
• Make your compare() smart enough to handle division by zero.
In the case of division by zero, let compare() return -2 to main()
and let main() print a suitable error message to std::cerr. After
printing the error message, main() should return an error code
of 1, rather than the usual 0, to the operating system; so let it do
so. (The return value -2 mentioned above, to which one imputes
a special or irregular meaning for the purpose of interrupting the
normal flow of execution, is called a sentinel.)
Scope variables appropriately. Call the source compare_ratios2.cpp.
Show that your program works by comparing 4/7 respectively to 35/61,
34/61 and 12/21.
Explanation / Answer
please rate - thanks #include <iostream>using std::cout;
using std::cin;
using std::cerr;
using std::endl;
int compare( int, int, int, int ) ;
int main()
{int a,b,c,d,result;
cout<<"Enter first numerator: ";
cin>>a;
cout<<"enter first denominator: ";
cin>>b;
cout<<"Enter second numerator: ";
cin>>c;
cout<<"enter second denominator: ";
cin>>d;
result=compare(a,b,c,d);
if(result==1)
cout<<"The ratio "<<a<<"/"<<b<<" is the larger. ";
else if(result==-1)
cout<<"The ratio "<<c<<"/"<<d<<" is the larger. ";
else if(result==0)
cout<<"The two ratios are equal. ";
else if(result==-2)
{cerr<<"division by 0 undefined ";
return 1;
}
return 0;
}
int compare( int n1, int d1, int n2, int d2)
{ double f1,f2;
if(d1==0||d2==0)
return -2;
f1=n1/(double)d1;
f2=n2/(double)d2;
if(f1==f2)
return 0;
else if(f1<f2)
return -1;
else
return 1;
}
)>
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.