[0415] C + + Simple programming-Class 4 and Object 2

Source: Internet
Author: User
Tags abs gcd string back

Experimental Report of Nanjing University of Information Engineering

Experiment name Class and Object 2 experimental date 2018-4-17 score Guide Teacher Shan Department of Soft College professional embedded + soft-embedded grade 2017 shift (1) name Schhao Yang School number 20161334026

First, the purpose of the experiment
    1. Mastering the design, definition, implementation, and testing of classes
    2. A deep understanding of the difference between object-oriented programming thinking and structured programming thinking
II. Preparation of the experiment

Before the experiment, please review/learn the content around the following content

    1. Multi-file structure of a C + + program organized in project file mode
      Study material "5.6.1 general organizational structure of C + + program"
    2. Compiling pre-processing directives
      Learning materials "5.6.4 section compiling pre-processing instructions"
    3. Definition and use of classes and objects
      Review the 4th chapter related content
Iii. contents of the experiment
    1. Practice writing a C + + program in a multi-file structure organized by a project file
      Rewrite the 4-20 in Experiment 3 as a multi-file structure

    2. Based on the existing information, to complement and expand the program, the realization of object-oriented programming and structured programming thinking different. There are three files available in the graph folder
      Based on the existing information, to complement and expand the program, the realization of object-oriented programming and structured programming thinking different.
      There are three files available in the graph folder

file Document Content Description
Graph.h Declaration of Class Graph
Graph.cpp The implementation of class Graph
Main.cpp Class Graph testing: Defining objects for the graph class, calling the public interface to draw graphics

Requirements are as follows:

    • Create a new project, add the above three files to the project.

    • Complements the implementation of the member function draw () of the class in Graph.cpp, enabling the test of the class in main () to achieve the following display effect:

Code effect
    • Extending the function of class Graph (optional)
      • Support to reset the displayed characters, dimensions, and automatically redraw the graphics after each reset;
      • Support graphics foreground color, background color setting and adjustment;
      • Supports control of horizontal or vertical movement of the graph through the arrow keys, etc.
    1. Design, define, and implement class fraction based on requirements description, and write code to complete the test.
      The specific requirements are described as follows:
      Design a class fraction describe fractions (ratios of two integers)

      The data members of the class fraction include two int variable top and bottom, which represent the numerator and denominator, respectively.

      After analysis, the following requirements are implemented by designing and implementing interfaces (that is, member functions):
    • List of basic features of class fraction
      • When defining a fraction class object, the following forms are supported:

        Tip: You write a constructor implementation and, based on different scenarios, write overloaded constructors.
      • The faction class object can do the following:
        • Add, subtract, multiply, divide operations
        • Compares two values and returns their size relationship
        • Input and output of fractions
      • Implemented by defining member functions. When designing each member function, consider the following:
        • function of the member function;
        • Whether parameters and return values are required, if required, a few arguments, what the type of the parameter is, what the type of the return value is
    • Extended functionality of class fraction (optional)
      • The score is normalized to ensure that the score is in the form, only the numerator is negative, and the fractional value is the reduction form.
        That
        2/-3 is normalized and converted to-2/3
        15/21 after normalization, convert to 5/7
        -2/-6 converted to 1/3 after normalized processing
      • Implementing a conversion between fractions to decimal
        Example: 3/4 will be converted to 0.75 output
    • Once you have designed and implemented a good Fracton class, test it in main () to ensure that the functions of the classes you design and implement are functioning properly.

    • Written in a multi-file structure organized by the project file (Fraction.h, Fraction.cpp, main.cpp)

Iv. conclusion of the experiment 0. Experimental Content 1
    • How to create a multi-file structure project in Dev-cpp
      • FILE-New-project
      • Add Project.h, Project.cpp, Main.cpp to the project
      • GIF Demo
    • C + + Code: see above
    • Java Code:

      Complex.javapackage ex1;public class Complex {private double real;private double imaginary;public Complex(double r0,double i0){    real = r0;    imaginary = i0;}public Complex(double r0){    real = r0;    imaginary = 0;}public Complex(Complex c0){    real = c0.real;    imaginary = c0.imaginary;}public void add(Complex c0) {    real += c0.real;    imaginary += c0.imaginary;}public void show() {    if (imaginary > 0) System.out.println(real + "+" + imaginary + "i");    else if(imaginary < 0) System.out.println(real + "-" + imaginary + "i");    else System.out.println(real);}}
    • Console

1. Experimental Content 2
  • Graph graph1(‘*‘,5);image analysis based on the draw () algorithm:
    The number of symbols output for each line is 2X line number +1, the output space is 2X total number +1-the number of symbols per line of output.
  • Lab Environment: Dev C + + 5.11
  • C + + Code:
    • Graph.cpp:

      #define rap(a,b) for(int a=1;a<=b;++a)#include<iostream>#include"Graph.h"using namespace std;Graph::Graph(char s,int l){sign=s;line=l;}void Graph::draw(){rap(i,line){int tmp=line-i;//cout<<tmp<<endl;rap(j,tmp) cout<<" ";rap(j,2*i-1)cout<<sign;rap(j,tmp) cout<<" ";cout<<endl;}return ;}
    • GRAPH.H:

      class Graph{protected:char sign;int line;       public:Graph(char s,int l);void draw();};
    • Main.cpp:

      #include "Graph.h"int main(){Graph graph1('*',5);graph1.draw();Graph graph2('$',7);graph2.draw();return 0;}
  • Java Code:
    • Graph.java:

      public class Graph {private static char sign;private static int line;public Graph(char s, int l) {sign = s;line = l;}public void draw() {for(int i = 1; i <= line; ++ i) {    int tmp = line - i;    for(int j = 1; j <= tmp; ++j) System.out.print(" ");    for(int j = 1; j <= 2*i-1; ++j) System.out.print(sign);    for(int j = 1; j <= tmp; ++j) System.out.print(" ");    System.out.print("\n");}}public void renew(char s, int l) {sign = s;line = l;draw();}}
    • Main.java:

      public static void main(String[] args) {// TODO 自动生成的方法存根Graph graph1=new Graph('*', 5);graph1.draw();Graph graph2=new Graph('$', 7);graph2.draw();graph2.renew('%', 8);}
  • Console

  • Optional parts:
    • Reset the displayed characters and dimensions:
      • Code (GRAPH.H):void rewrite(char s,int l);
      • Code (Graph.cpp):

      • Code (Main.cpp):graph2.rewrite(‘%‘,8);
      • Demonstrate:

    • Support graphics foreground color, background color setting and adjustment;
      • To set the color of the console output:

        HANDLE consolehwnd=GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleTextAttribute(consolehwnd,Color);
        where color is a 8-bit binary number, high storage foreground color, low storage background color.
      • Color number
      • Code (GRAPH.H):

        protected unsigned int forecolor,backcolor;int str2color(string a);
      • Code (Graph.cpp):

          int Graph::str2color (string a) {if (strcasecmp (A.c_str (), "black") = = 0) return 0 if (strcasecmp (A.c_str (), "blue") = = 0) return 1;if (strcasecmp (A.c_str (), "green") = = 0) return 2;if (strcasecmp (A.c_str ( ), "lackblue") = = 0) return 3;if (strcasecmp (A.c_str (), "red") = = 0) return 4;if (strcasecmp (A.c_str (), "purple") = = 0) retur N 5;if (strcasecmp (A.c_str (), "yellow") = = 0) return 6;if (strcasecmp (A.c_str (), "white") = = 0) return 7;if (strcasecmp (a.c_ STR (), "grey") = = 0) return 8;return 0;} void Graph::setcolor (string fore, string back) {Forecolor=str2color (fore); Backcolor=str2color (back);} void Graph::d raw () {HANDLE consolehwnd=getstdhandle (std_output_handle); Setconsoletextattribute (Consolehwnd, (forecolor<<4) +backcolor);}  
      • Code (Main.cpp):

        #include "Graph.h"int main(){Graph graph1('*',5);graph1.setcolor("white","red");graph1.draw();Graph graph2('$',7);graph2.setcolor("blue","yello");graph2.draw();graph2.setcolor("grey","green");graph2.rewrite('%',8);return 0;}
      • Console

    • The arrow keys control the graphics movement:
      • Code (Main.cpp):

        while(1){int ch=getch();switch(ch){case 72:if(offsety>0)offsety--;break;case 75:if(offsetx>0)offsetx--;break;case 77:offsetx++;break;case 80:offsety++;break;}system("cls"); graph2.redraw(offsetx,offsety);}
      • Code (GRAPH.H):void redraw(int x,int y);
      • Code (Graph.cpp):

        void Graph::redraw(int x,int y){rap(j,y)cout<<endl;rap(i,line){int tmp=line-i;rap(j,x)cout<<" ";rap(j,tmp) cout<<" ";rap(j,2*i-1)cout<<sign;rap(j,tmp) cout<<" ";cout<<endl;}}
      • Demo GIF:

2. Experimental Content 3
  • UML Class Diagrams:
  • Code:
    • Fraction.java

      Package Ex3;import Java.util.scanner;public class Fraction {private int top;private int bottom;private int gcd (int a, int b) {return a% b = = 0? b:gcd (b, a%b);} private int ABS (int a) {return a > 0? A:-A;} public fraction (int t, int b) {top = T;bottom = b;} public fraction (int t) {top = T;bottom = 1;} Public fraction () {top = 0;bottom = 1;}    public void Simplify () {if (bottom < 0) {top =-top; bottom =-bottom;} int g = GCD (ABS (top), ABS (bottom)), top/= g;bottom/= g;} public void Add (fraction c0) {bottom = bottom * C0.bottom;top = top * c0.bottom + c0.top * bottom;simplify ();}      public void subtract (fraction c0) {bottom = bottom * C0.bottom;top = top * c0.bottom-c0.top * bottom;if (Bottom < 0) {    top =-top; bottom =-bottom;} Simplify ();} public void multiple (fraction c0) {top *= c0.top;bottom *= c0.bottom;simplify ();}    public void Divde (fraction c0) {if (C0.top = = 0) {System.out.println ("Error:zero can ' t be divided."); return;} Top *= c0.bottom;bottom *= c0.tOp;simplify ();} public boolean compare (fraction c0) {return top * GCD (bottom, C0.bottom)-C0.top * GCD (bottom, c0.bottom) > 0 ? True:false;} @SuppressWarnings ("resource") public void Readln () {Scanner sc=new Scanner (system.in);     SYSTEM.OUT.PRINTLN ("Plz input the numerator and denominator"); top = Sc.nextint (); int tmp = Sc.nextint (); while (tmp = = 0) {    System.out.println ("Zero can ' t be the denominator, plz try again!"); TMP = Sc.nextint ();} bottom = tmp;} public void Writeln () {if (bottom! = 1) System.out.println (top + "/" + bottom); else System.out.println (top);} Public double ToDecimal () {return (double) Top/bottom;}}
    • Main.java

      package ex3;public class Main {public static void main(String[] args) {// TODO 自动生成的方法存根Fraction c1 = new Fraction (11,22);Fraction c2 = new Fraction (4);Fraction c3 = new Fraction ();c1.add(c2);c1.writeln();c1.subtract(c2);c1.writeln();c1.multiple(c2);System.out.println(c1.todecimal());c1.writeln();c1.divde(c2);c1.writeln();}}
    • Fraction.h

      #include<iostream>#include<cmath>using namespace std;class Fraction{protected:int top, bottom;int gcd(int a, int b);public:Fraction(int t, int b);Fraction(int t);Fraction();void simplify();void add(Fraction c0);void subtract(Fraction c0);void multiple(Fraction c0);void divde(Fraction c0);bool compare(Fraction c0);void readln();void writeln();double todecimal();};
    • Fraction.cpp

      int fraction::gcd (int a, int b) {return a% b = = 0? b:gcd (b, a%b);} fraction::fraction (int t, int b) {top = T;bottom = b;} fraction::fraction (int t) {top = T;bottom = 1;} Fraction::fraction () {top = 0;bottom = 1;} void Fraction::simplify () {if (bottom < 0) {top =-Top;bottom =-bottom;} int g = GCD (ABS (top), ABS (bottom)), top/= g;bottom/= g;} void Fraction::add (fraction c0) {bottom = bottom * C0.bottom;top = top * c0.bottom + c0.top * bottom;simplify ();} void Fraction::subtract (fraction c0) {bottom = bottom * C0.bottom;top = top * c0.bottom-c0.top * bottom;if (Bottom < 0 {top =-Top;bottom =-bottom;} Simplify ();} void Fraction::multiple (fraction c0) {top *= c0.top;bottom *= c0.bottom;simplify ();} void fraction::d ivde (fraction c0) {if (C0.top = = 0) {cout << "Error:zero can ' t be divided.\n"; return;} Top *= c0.bottom;bottom *= c0.top;simplify ();} BOOL Fraction::compare (fraction c0) {return top * GCD (bottom, C0.bottom)-c0.top* gcd (bottom, C0.bottom) > 0? true: false;} voidFraction::readln () {cout << "Plz input the numerator and denominator" << endl;cin >> top;int tmp;cin ;> tmp;while (tmp = = 0) {cout << "Zero can ' t be the denominator, plz try again!" << endl;cin >> tmp;} bottom = tmp;} void Fraction::writeln () {if (bottom! = 1) cout << top << "/" << bottom << endl;else cout << Top <<endl;} Double Fraction::todecimal () {return (double) Top/bottom;}
    • Main.cpp

      #include "Fraction.h"#include <iomanip>int main() {Fraction c1 (11,-22);Fraction c2 (4);Fraction c3 ;c1.writeln();c1.add(c2);c1.writeln();cout << fixed<< setprecision(2) << c1.todecimal() << endl;c1.subtract(c2);c1.writeln();c1.multiple(c2);c1.writeln();c1.divde(c2);c1.writeln();return 0;}
  • Console
  • Optional parts:
    • Planning Processing:

      void Fraction:: simplify() {if(bottom < 0) {top = - top;bottom = - bottom;}int g = gcd(abs(top),abs(bottom));top /= g;bottom /= g;}
    • Convert to decimal:

      double Fraction:: todecimal() {return (double)top / bottom;}
Five, the experiment summary and experience
    • Multi-file structured projects are more likely to be co-operative in future real-world development.
    • As a Java derived from C + +, everything must be placed into a class, with no class declaration, only class definitions.
    • My pleasure to participate in the design of this experiment~

[0415] C + + Simple programming-Class 4 and Object 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.