当前位置: 首页 > 工具软件 > kint > 使用案例 >

double与int

闻人昕
2023-12-01

double与int不能混用!

结果为小数,必须用double,否则一直输出0,真的折磨人!

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
using namespace std;
float a[1005];
#define PI 3.1415927
int main() {
	int n, max, min, k,s, sum;
	//double s;
	while (~scanf("%d", &n)) {
		sum = 0;
		scanf("%d", &k);
		max = min = k;
		sum += k;
		for (int i = 0; i < n - 1; i++) {
			scanf("%d", &k);
			if (k > max) max = k;
			if (k < min) max = k;
			sum += k;
		}
		
		s = (1.0 * (sum - max - min)) / (n - 2);
		printf("%.2f\n", s);
	}
	return 0;
}

可以看到,我这里就是犯了一个小错误——结果是要我输出小数,我却把结果定义成了int型,结果无论我怎么输入,他都给你输出一个0.00。以后必须得注意啦~~~
正确代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
using namespace std;
float a[1005];
#define PI 3.1415927
int main() {
	int n, max, min, k, sum;
	double s;
	while (~scanf("%d", &n)) {
		sum = 0;
		scanf("%d", &k);
		max = min = k;
		sum += k;
		for (int i = 0; i < n - 1; i++) {
			scanf("%d", &k);
			if (k > max) max = k;
			if (k < min) max = k;
			sum += k;
		}
		
		s = (1.0 * (sum - max - min)) / (n - 2);
		printf("%.2f\n", s);
	}
	return 0;
}
 类似资料: