How do I round up the solution? Question: Ask the user for a number between 5 an
ID: 3850573 • Letter: H
Question
How do I round up the solution?
Question:
Ask the user for a number between 5 and 30. For each number between 1 and the number entered, display the value 1/that number, as a ratio and a decimal value. Round up on .005 and above. For example:
Use the following format specifiers to get the precision of the output to match:
Current Code:
#include <iostream>
#include<iomanip> //for formatting
using namespace std;
int main(){
int n;
cout<<"Please enter a number (5 to 30): ";
cin>>n;
cout << n << endl;
cout << fixed << setprecision(2); //to print upto 2 decimal places
if(n < 5 || n > 30){
cout<<"Please follow the directions! ";}
else{
for(int i=1; i<=n;i++){
cout<<"1/"<<i <<" is "<<1.0/i<<endl;}}
return 0;}
Outputs:
5. Compare output 15 nput Please enter a number (5 to 30) 15 1/1 is 1.00 1/2 is 50 1/3 is 0.33 1/4 is 0.25 1/5 is 0.20 1/6 is 0.17 1/7 is 0.14 Your output 1/8 is 0.12 1/9 is 0.11 1/10 is 0.10 1/11 is 0.09 1/12 is 0.08 1/13 is 0.08 1/14 is 0.07 1/15 is 0.07 Please enter a number (5 to 30) 15 1/1 is 1.00 1/2 is 50 1/3 is 0.33 1/4 is 0.25 1/5 is 0.20 1/6 is 0.17 1/7 is 0.14 Expected output 1/8 is 0.13 1/9 is 0.11 1/10 is 0.10 1/11 is 0.09 1/12 is 0.08 1/13 is 0.08 1/14 is 0.07 1/15 is 0.07Explanation / Answer
You need to right a function to do that for you, Please find the function below.
#include <iostream>
#include<iomanip> //for formatting
using namespace std;
#include <cmath>
double settingprecision(double input, int precision) {
return
ceil( input * pow(10,(double)precision) - .4999999999999)
/ pow(10,(double)precision);
}
int main(){
int n;
cout<<"Please enter a number (5 to 30): ";
cin>>n;
cout << n << endl;
cout << fixed << setprecision(2); //to print upto 2 decimal places
if(n < 5 || n > 30){
cout<<"Please follow the directions! ";}
else{
for(int i=1; i<=n;i++){
cout<<"1/"<<i <<" is "<<settingprecision(float((float)1.0/(float)i),2)<<endl;}}
return 0;}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.