转载部分:
浮点错误: 您的程序运行时发生浮点错误,比如遇到了除以 0 的情况
所以发生浮点错误应该考虑程序中:
是否可能出现了一个数除以0的情况
是否可能出现了一个数取余0的情况
是否发生了数据溢出而导致的除以0或者取余0的情况
我的错误是 用int类型除int类型
正确的做法是 先把被除数转换为 double类型 比较简单的办法是
乘1.0
如:
nod[i].ratio = 1.0*nod[i].price / nod[i].storel;
下面贴代码
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
const int Max = 1010;
typedef struct {
int storel;
int price;
double ratio;
}Nod;
Nod nod[Max];
void scanff(int nc) {
for (int i = 0; i < nc; i++) {
scanf("%d", &nod[i].storel);
}
for (int i = 0; i < nc; i++) {
scanf("%d", &nod[i].price);
}
}
bool cmp(Nod nod1,Nod nod2) {
if (nod1.price != nod2.price)
return nod1.ratio > nod2.ratio;
return 0;
}
double tanxin(int dc, int nc) {
int i = 0;
double prof = 0.0;
while (dc != 0.0 && nc != 0) {
if (dc >= nod[i].storel) {
dc -= nod[i].storel;
prof += nod[i].price;
}
else {
//nod[i].storel -= dc / nod[i].ratio;
prof += dc*nod[i].ratio;
dc = 0;
}
i++;
nc--;
}
return prof;
}
int main()
{
freopen("Text.txt", "r", stdin);
int n = 0, d = 0;
double profit = 0.0;
while (scanf("%d %d",&n,&d)!=EOF) {
scanff(n);
for (int i = 0; i < n; i++) {
nod[i].ratio = 1.0*nod[i].price / nod[i].storel;
}
sort(nod, nod + n, cmp);
profit = tanxin(d, n);
printf("%.02lf\n", profit);
}
return 0;
}