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;
}

 

上一篇:【题解】比例简化


下一篇:静态查看进程信息 -- 基于 ps 命令实现