-2

I can seem to print the real part of a complex number using printRe in my class.

As a test I get complex number p(1.0, 5.0) where the real number is 1.0 and imaginarynumber5.0 I would like to return real number, so1.0`. The function should return

real number(Real number is: 1.0)

But when I run my code, I get only

"Real number is: "

Where is the problem Here is my code:

#include <iostream>
#include <stdio.h>
using namespace std;

class Complex{
public:
    double a;
    double b;

    Complex(double re=0.0, double im=0.0){
        a = re;
        b = im;
    }

    Complex(const Complex &other){
        a = other.a;
        b = other.b;
    }

    void printRe(){
        printf("Real number is:", a);
    }

};


 //some operators +, -, *, /

int main(){

    Complex p(1.0, 5.0);
    p.printRe();

    return 0;

}

Would appreciate some help

David
  • 8,113
  • 2
  • 17
  • 36
Janyl S
  • 49
  • 6

2 Answers2

2

you should change the printf line to:

printf("Real number is: %f", a);

That should output the desired real part

I would suggest that you read about the printf function and how to properly use it in the following link: printf

In C++ it is more common to use the cout rather then printf you can read about it also: cout

The cout way is:

std::cout << "Real number is:" << a << std::endl;
David
  • 8,113
  • 2
  • 17
  • 36
2

You have two options to display/print to your standard output.

Try this (preferred method in C++):

std::cout << "Real number is: " << a << std::endl;

Or, Use correct format specifier with printf.

printf("Real number is: %f\r\n", a);

In printf, a format specifier follows this prototype:

%[flags][width][.precision][length]specifier

Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument.

f   Decimal floating point, lowercase                   392.65
F   Decimal floating point, uppercase                   392.65
e   Scientific notation (mantissa/exponent), lowercase  3.9265e+2
E   Scientific notation (mantissa/exponent), uppercase  3.9265E+2
g   Use the shortest representation: %e or %f           392.65
G   Use the shortest representation: %E or %F           392.65
a   Hexadecimal floating point, lowercase               -0xc.90fep-2
A   Hexadecimal floating point, uppercase               -0XC.90FEP-2

If you want to control the precision of float, you can visit this question for printf or visit this for cout.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
abhiarora
  • 9,743
  • 5
  • 32
  • 57