浮点错误

转载部分:

浮点错误: 您的程序运行时发生浮点错误,比如遇到了除以 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;
}

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值