C/C++ Programming Learning-Week 5 ⑥ Rounding off

Topic link

Title description

Give you a floating-point number n, which requires rounding to two decimal places.

Input format
A floating point number n (0 ≤ n ≤ 100).

Output format
A floating-point number, which means that the result of n with two decimal places.

Sample Input

3.14159

Sample Output

3.14

Ideas

You can output directly, or you can write a rounding function to output.

C language code:

#include<stdio.h>
int main()
{
    
    
	double n;
	scanf("%lf", &n);
    printf("%.2lf", n);
    //cout << fixed << setprecision(2) << n;//c++的cout格式化输出
    return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
double Round(double r)
{
    
    
	return floor(r * 100.0 + 0.5) / 100.0;
}
int main()
{
    
    
	double n;
	while(cin >> n)
		printf("%.2lf\n", Round(n));
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112909418