疑问
关于“stdio.h”与“cstdio”的使用场景一直不会。。。唉
代码
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 110;
//注意,是long long
struct Fraction{
long long up;
long long down;
}fracs[maxn];
int n;
//求最大公约数
long long gcd(long long a,long long b){
if(b == 0){
return a;
}else{
return gcd(b,a%b);
}
}
//化简分数
Fraction reduction(Fraction result){
if(result.down < 0){
result.down = -result.down;
result.up = -result.up;
}
if(result.up == 0){
result.down = 1;
}else{
long long num = gcd(abs(result.up),abs(result.down));
result.up = result.up / num;
result.down = result.down / num;
}
return result;
}
//加法
Fraction add(Fraction f1,Fraction f2){
Fraction result;
result.up = f1.up*f2.down + f2.up * f1.down;
result.down = f1.down * f2.down;
return reduction(result);
}
//展示结果
void showResult(Fraction r){
r = reduction(r);
//首先看是不是整数
if(r.down == 1){
printf("%lld",r.up);
}else if(abs(r.up) > abs(r.down)){
//看是不是假分数
printf("%lld %lld/%lld",r.up/r.down,abs(r.up)%r.down,r.down);
}else{
printf("%lld/%lld",r.up,r.down);
}
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%lld/%lld",&fracs[i].up,&fracs[i].down);
//进行化简
fracs[i] = reduction(fracs[i]);
}
//和sum初始化为0
Fraction sum;
sum.down = 1;
sum.up = 0;
for(int i=0;i<n;i++){
sum = add(sum,fracs[i]);
}
showResult(sum);
return 0;
}
反思
- 题中说的
long int
是指int
,long long int
才是long long
。由于int
之间的乘法可能会溢出,所以要使用long long
; abs()
一般都用<algorithm>
里面的,不用math
里的;- 自顶向下,逐步求精。。。
二刷代码
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 110;
typedef long long ll;
struct fraction{
ll up;
ll down;
fraction(){
up = 0;
down = 1;//初始化为0
}
};
ll gcd(ll a,ll b){
if(b==0){
return a;
}else{
return gcd(b,a%b);
}
}
fraction reduction(fraction f){
if(f.down<0){
f.up = -f.up;
f.down = -f.down;
}
if(f.up==0){
f.down=1;
}else{
//化简
ll common = gcd(abs(f.up),f.down);
f.up = f.up/common;
f.down = f.down/common;
}
return f;
}
fraction add(fraction a,fraction b){
fraction res;
ll up = a.up*b.down + b.up*a.down;
ll down = a.down*b.down;
res.up = up;
res.down = down;
res = reduction(res);//注意化简
return res;
}
void show(fraction a){
//首先化简
a = reduction(a);
//如果是整数,包括0~
if(a.down==1){
printf("%lld",a.up);
}else{
if(abs(a.up)>a.down){
printf("%lld %lld/%lld",a.up/a.down,abs(a.up)%a.down,a.down);
}else{
//直接输出
printf("%lld/%lld",a.up,a.down);
}
}
}
int n;
fraction in[maxn];
int main(){
scanf("%d",&n);
fraction res;
for(int i=0;i<n;i++){
ll up,down;
scanf("%lld/%lld",&up,&down);
fraction cur;
cur.up = up;
cur.down = down;
cur = reduction(cur);
res = add(res,cur);
}
//接下来就是表示
show(res);
return 0;
}