1. 程式人生 > >pat乙級1034

pat乙級1034

inf 超出 不能 clu div sin can add pre

1.vs2013不能用scanf,改為scanf_s,但是提交時不能用scanf_s,用scanf。。。

1 scanf_s("%lld/%lld %lld/%lld", &a[0], &a[1], &b[0], &b[1]);

2.c++中數組作為函數參數時傳遞的是地址,會改變實參的值。

3.用printf輸出string型變量時要加上“.c_str()”:

1 printf("%s + %s = %s\n", simple(a).c_str(), simple(b).c_str(), simple(r).c_str());

4.類型別名:

1 using LL = long
long;

相乘時可能會超出整型範圍,用long long。

代碼:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 using LL = long long;//類型別名
 5 
 6 LL gcd(LL a, LL b)
 7 {
 8     if (b == 0)
 9         return a;
10     return gcd(b, a % b);
11 }
12 
13 string simple(LL a[2])
14 {
15     LL m = a[0
], n = a[1]; 16 if (n < 0) 17 { 18 m = -m; 19 n = -n; 20 } 21 string s; 22 char c; 23 if (m < 0) 24 { 25 m = -m; 26 c = -; 27 } 28 else c = +; 29 30 LL g = gcd(m, n);//分子分母最大公約數 31 m = m / g; 32 n = n / g; 33 34 LL r = m % n;
35 LL k = m / n; 36 if (k) s = to_string(k); 37 if (r && k) s += " "; 38 if (r) s = s + to_string(r) + "/" + to_string(n); 39 if (!k && !r) s = "0"; 40 41 if (c == -) s = "(-" + s + ")"; 42 return s; 43 } 44 void add(LL a[2], LL b[2]) 45 { 46 LL r[2]; 47 r[0] = a[0] * b[1] + b[0] * a[1]; 48 r[1] = a[1] * b[1]; 49 printf("%s + %s = %s\n", simple(a).c_str(), simple(b).c_str(), simple(r).c_str()); 50 } 51 void sub(LL a[2], LL b[2]) 52 { 53 LL r[2]; 54 r[0] = a[0] * b[1] - b[0] * a[1]; 55 r[1] = a[1] * b[1]; 56 printf("%s - %s = %s\n", simple(a).c_str(), simple(b).c_str(), simple(r).c_str()); 57 } 58 void motify(LL a[2], LL b[2]) 59 { 60 LL r[2]; 61 r[0] = a[0] * b[0]; 62 r[1] = a[1] * b[1]; 63 printf("%s * %s = %s\n", simple(a).c_str(), simple(b).c_str(), simple(r).c_str()); 64 } 65 void divide(LL a[2], LL b[2]) 66 { 67 LL r[2]; 68 r[0] = a[0] * b[1]; 69 r[1] = a[1] * b[0]; 70 if (r[1]) 71 printf("%s / %s = %s\n", simple(a).c_str(), simple(b).c_str(), simple(r).c_str()); 72 else 73 printf("%s / %s = Inf\n", simple(a).c_str(), simple(b).c_str()); 74 } 75 int main() 76 { 77 LL a[2], b[2]; 78 scanf_s("%lld/%lld %lld/%lld", &a[0], &a[1], &b[0], &b[1]); 79 80 add(a, b); 81 sub(a, b); 82 motify(a, b); 83 divide(a, b); 84 85 return 0; 86 }

pat乙級1034