poj1079

1.链接地址

https://vjudge.net/problem/POJ-1064#author=0

2.问题描述

For example, if 5 stocks rose in price and 4 fell, the best approximation with denominator 1 is 1/1; that is, for every stock that fell, about one rose. This answer differs from the exact answer by 0.25 (1.0 vs 1.25). The best approximations with two in the denominator are 2/2 and 3/2, but neither is an improvement on the ratio 1/1, so neither would be considered. The best approximation with three in the denominator 4/3, is more accurate than any seen so far, so it is one that should be reported. Finally, of course, 5/4 is exactly the ratio, and so it is the last number reported in the sequence. 

Can you automate this process and help the anchorpeople? 

输入样例

5 4 
1498 902 

输出样例

1/1 
4/3 
5/4 

2/1 
3/2 
5/3 
48/29 
53/32 
58/35 
63/38 
68/41 
73/44 
78/47 
83/50 
88/53 
93/56 
377/227 
470/283 
563/339 
656/395 
749/451

3.解题思路

给出一个分数,比如1498/902。求出当分母分别为1, 2, ....的时候,最接近1498/902的分数。
当分母为1的时候,最接近1498/902的分数为 1/1。
当分母为2的时候,最接近1498/902的分数为 3/2。
当分母为3的时候,最接近1498/902的分数为 5/3。
以此类推

4.算法实现源代码

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    
    int den_init,num_init;  
    int den, num;  
    int num_temp;   
    int i = 0;
    while (cin >> num_init >> den_init)  
    {
        num = 1;  
        den = 0;  
 
        for (i = 1; i <= den_init; i++)   
        {
            num_temp = (int)((double)(i*num_init) / (double)den_init + 0.5); 
            if (den*abs(num_init*i - den_init*num_temp) < i*abs(num_init*den - den_init*num))
            {
                num = num_temp;
                den = i;
                cout << num << "/" << den << endl;
            }
            if (den_init*num == num_init*den) break;  
        }
        cout << endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/KasenBob/p/11221017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值