Answer on Question #50915, Programming, C++
Problem.
Write a program that allows a user to enter 10 floating-point values into an array. Then, in a loop, the program should prompt the user for a desired precision and subsequently display each value to the correct precision. The loop continues prompting for a precision and displaying the 10 values until the user enters a negative value for the precision. Save the file as PrecisionRequest.cpp.
Code.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
float arr[10];
int precision;
// Input
cout << "Please enter 10 floating-point numbers: ";
for (int i = 0; i < 10; i++) {
cin >> arr[i];
}
do {
// Reading precision
cout << "Enter precision: ";
cin >> precision;
if (precision >= 0) {
char format[4];
sprintf(format, "%%.%df", precision);
for (int i = 0; i < 10; i++) {
printf(format, arr[i]);
if (i != 9) {
printf(" ");
} else {
printf("\n");
}
}
}
} while(precision >= 0);
}Output.
Please enter 10 floating-point numbers: 0 1 2 3 4 5 6 7 8 9
Enter precision: 1
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
Enter precision: 2
0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00
Enter precision: -1
https://www.AssignmentExpert.com</cstdio></iostream>
Comments