rop.inp 파일에서 수를 읽어와서 rop.out 파일로 수를 출력합니다.
fprintf, fscanf 활용해야하구요.
2번째 라인의 정수 N을 활용해서 결과를 출력합니다. N이 0일경우 더하기, N이 1일경우 곱하기, N이 2일경우 나누기입니다.
예를 들어 입력파일에
1 2
0
3 5
이렇게 입력되어있을경우
1/2 + 3/5라는 뜻이되고 11/10이 됩니다.
따라서 출력파일에 11/10이 표시되어야합니다.
다른 예를 들면
3 2
1
4 5
이렇게 입력되었을경우
3/2 * 4/5라는 뜻이되고 출력은 6/5가 됩니다.
아래는 짠 코드이니 한번 살펴봐주십시오.. 오류가계속납니다.
이게오류구요 ㅠㅠ
=======================================================================================
1>c:\users\jang\documents\visual studio 2010\projects\rop\rop\rop.cpp(54): error C2628: 'Rational' 다음에 'int'이(가) 올 수 없습니다. ';'이 있어야 합니다.
1>c:\users\jang\documents\visual studio 2010\projects\rop\rop\rop.cpp(54): error C3874: 'main'의 반환 형식이 'int'이어야 하는데 'Rational'입니다.
1>c:\users\jang\documents\visual studio 2010\projects\rop\rop\rop.cpp(79): error C2664: 'Rational::Rational(const Rational &)' : 매개 변수 1을(를) 'int'에서 'const Rational &'(으)로 변환할 수 없습니다.
1> 원인: 'int'에서 'const Rational'(으)로 변환할 수 없습니다.
1> 소스 형식을 가져올 수 있는 생성자가 없거나 생성자 오버로드 확인이 모호합니다.
=======================================================================================
#include <iostream>
#include <cstdio>
using namespace std;
class Rational {
private:
int a; // 분자
int b; // 분모
public:
Rational() {
this->a = 0; this->b = 1;
}
Rational(int a, int b) {
this->a = a; this->b = b;
}
public:
int getA() { return a; }
int getB() { return b; }
Rational add(const Rational & value) {
// 두 분수의 분자분모 크로스 해서 곱함
int t1 = this->a * value.b;
int t2 = this->b * value.a;
int t = t1 + t2;
int u = this->b * value.b;
// 결과 값의 분자 분모 최대공약수 구함
int s = this->gcd(t, u);
// 나눠 약분한 값 리턴
return Rational(t / s, u / s);
}
Rational mul(const Rational & value) {
// 두 분수의 분자끼리 분모끼리 곱함.
int t = this->a * value.a;
int u = this->b * value.b;
// 결과 값의 분자 분모 최대공약수 구함
int s = this->gcd(t, u);
// 나눠 약분한 값 리턴
return Rational(t / s, u / s);
}
Rational div(const Rational & value) {
// 두분수의 분자분모 크로스해서 곱하면 나눗셈.
int t = this->a * value.b;
int u = this->b * value.a;
// 결과 값의 분자 분모 최대공약수 구함
int s = this->gcd(t, u);
// 나눠 약분한 값 리턴
return Rational(t / s, u / s);
}
// 유클리드 알고리즘 이용해 최대공약수 구합니다.
int gcd(int t, int u) {
if(u == 0) return t; // 뒤의 수가 0이면 앞의수가 최대공약수가 되어 리턴
if(t < u) return this->gcd(u, t); // 뒤의 수가 더 크면 순서 바꿔서 재계산
return this->gcd(t - u, u); // 앞-뒤 뺀 수와 뒤 수간의 공약수 구함
}
}
int main() {
FILE *fp1 = fopen("rop.inp", "r"); // 입력파일 읽기전용으로 읽기
FILE *fp2 = fopen("rop.out", "w"); // 출력파일 쓰기모드로 열기
int a, b, op, c, d; // 피연산자 2개와 연산자 하나
fscanf(fp1, "%d", &a);
fscanf(fp1, "%d", &b);
fscanf(fp1, "%d", &op);
fscanf(fp1, "%d", &c);
fscanf(fp1, "%d", &d);
Rational r1(a, b), r2(c, d); // 읽은 4 수로 분수 클래스 초기화
Rational out;
switch(op) { // 연산자에 따라
case 0 : // 0을 덧셈으로 정의했다면
out = r1.add(r2);
break;
case 1 : // 1을 곱셈으로 정의했다면
out = r1.mul(r2);
break;
case 2 : // 2를 나눗셈으로 정의했다면
out = r1.div(r2);
break;
}
fprintf(fp2, "%d/%d", out.getA(), out.getB()); // 결과 파일에 기록
fflush(fp2); // 쓰기 버퍼 비움
fclose(fp1); fclose(fp2); // 파일 닫기
return 0;
}
으헝 간단한걸 = _=