first question
My algorithm is to use two variables i and j to control the input of spaces and symbols, fill spaces first, then fill symbols, and then cover symbols with spaces
My code is as follows
int i,j; for(i=0;i<size;i++) { for(j=1;j<=2*size-1;j++) { if(j>=size-i&&j<=size+i) { cout<<symbol; } else cout<<" "; } cout<<endl; }
Development environment Dev-C++ 5.11
Question 2
Function declaration:
#pragma once #ifndef Fraction_h #define Fraction_h class Fraction { public: Fraction(int i,int j); Fraction(int i); Fraction(); ~Fraction(); void add(Fraction &a); void subtract(Fraction &a); void multiply(Fraction &a); void divide(Fraction &a); void compare(Fraction &a); void input(); void output(); private: int top; int bottom; }; #endif
Implementation of the function:
#include "Fraction.h" #include <iostream> using namespace std; Fraction::Fraction(int i,int j):top(i),bottom(j) {} Fraction::Fraction(int i):top(i) { bottom=1; } Fraction::Fraction() { top=0; bottom=1; } Fraction::~Fraction() {} void Fraction::add(Fraction &a) { cout<<top*a.bottom+a.top*bottom<<"/"<<bottom*a.bottom<<endl; } void Fraction::subtract(Fraction &a) { cout<<top*a.bottom-a.top*bottom<<"/"<<bottom*a.bottom<<endl; } void Fraction::multiply(Fraction &a) { cout<<top*a.top<<"/"<< bottom * a.bottom << endl; } void Fraction::divide(Fraction &a) { cout<<top*a.bottom<<"/"<< bottom * a.top << endl; } void Fraction::compare(Fraction &a) { if(top*a.bottom>bottom*a.top) cout<<top<<"/"<<bottom<<endl; else if(top*a.bottom<bottom*a.top) cout<<a.top<<"/"<<a.bottom<<endl; else if(top*a.bottom==bottom*a.top) cout << " as big as " << endl; } void Fraction::input() { cin>>top>>bottom; } void Fraction::output() { cout<<top<<"/"<<bottom<<endl; }
main function:
#include <iostream> #include "Fraction.h" using namespace std; intmain () { Fraction a; Fraction b(3,4); Fraction c(5); cout <<"a:"; a.output(); cout <<"b:"; b.output(); cout <<"c:"; c.output(); cout <<"a+b="; a.add(b); cout <<"a-b="; a.subtract(b); cout <<"a*b="; a.multiply(b); cout <<"a/b="; a.divide(b); cout << " Compare the size of a and b: " ; a.compare(b); cout << " Please enter the numerator and denominator: " ; a.input(); cout << " The size of a is: " ; a.output(); return 0; }
operation result:
Summarize:
After this experiment, I found that I still have many deficiencies, and this leads to my slow speed in solving problems, and I am not proficient in many things, especially knowledge about classes. I will seriously summarize, spend more effort on this class