PAT 乙级 1088

题目

    题目链接:PAT 乙级 1088

题解

    比较简单的一道题,下面来简单说说思路;

    因为甲确定是一个两位数,因此通过简单的暴力循环求解甲的值,又根据题设条件“把甲的能力值的 2 个数字调换位置就是乙的能力值;甲乙两人能力差是丙的能力值的 X 倍;乙的能力值是丙的 Y 倍”,可求得Y * |甲 - 乙| = X * 乙,且乙是甲的翻转,因此我们可以求得甲与乙的值,也可求出丙的值,即求得结果。

    但是在程序中忽略了一个问题,就是 (int a / int b) 的问题,我们来看一段样例程序

1 #include <iostream>
2 using namespace std;
3 
4 int main() {
5     cout << 3 / 2 << endl;
6     cout << 3.0 / 2 << endl;
7 
8     return 0;
9 }

    结果如下

1
1.5

    从结果我们就可以看出—— int / int 结果还是 int,float / int 结果才是期望的float,这一点需要注意;

    因为丙的值存在不是整数的可能性,因此需要获得float类型的结果,所以需要在两个整数的除法之前乘以1.0,即以1.0 * a / b 的形势。

代码

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 int fun (int x) {
 6     int sum = 0;
 7     sum += (x % 10) * 10;
 8     sum += x / 10;
 9     return sum;
10 }
11 
12 void out(int x, int I) {
13     if (x > I)
14         cout << "Cong";
15     else if (x < I)
16         cout << "Gai";
17     else if (x == I)
18         cout << "Ping";
19 }
20 
21 void out(double x, int I) {
22     if (x > I)
23         cout << "Cong";
24     else if (x < I)
25         cout << "Gai";
26     else if (x == I)
27         cout << "Ping";
28 }
29 
30 int main() {
31     int m = 0, x = 0, y = 0;
32     int a = 0, b = 0;
33     double c = 0;
34     int max_a = 0;
35     cin >> m >> x >> y;
36     for (int i = 10; i < 100; i++) {
37         a = i;
38         b = fun(i);
39         if (y * abs(a - b) == x * b) {
40             max_a = i;
41         }
42     }
43     if (max_a == 0)
44         cout << "No Solution" << endl;
45     else {
46         a = max_a;
47         b = fun(a);
48         c = 1.0 * b / y;
49         cout << a << ' ';
50         out(a, m); cout << ' ';
51         out(b, m); cout << ' ';
52         out(c, m); cout << endl;
53     }
54 
55     return 0;
56 }

    本题代码有些臃肿,将就着看看吧,不想优化了......

猜你喜欢

转载自www.cnblogs.com/moujun1001/p/9665709.html
今日推荐