簡體   English   中英

如何從復數返回實數

[英]How to return the real number from complex number

我似乎可以在我的班級中使用printRe打印復數的實部。

作為測試,我得到復數p(1.0, 5.0) ,其中實數為1.0 ,虛number 5.0 I would like to return real number, so 1.0`。 函數應該返回

實數(實數為:1.0)

但是當我運行我的代碼時,我只得到

“實數是:”

問題出在哪里這是我的代碼:

#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;

}

希望得到一些幫助

您應該將printf行更改為:

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

那應該輸出所需的實部

我建議您在以下鏈接中閱讀printf函數以及如何正確使用它: printf

C++ 中,使用cout而不是printf更常見,您也可以閱讀它: cout

cout方式是:

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

您有兩個選項可以顯示/打印到標准輸出。

試試這個(C++ 中的首選方法):

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

或者,對printf使用正確的格式說明符

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

在 printf 中,格式說明符遵循以下原型:

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

末尾的說明符字符是最重要的組成部分,因為它定義了其相應參數的類型和解釋。

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

如果你想控制浮點數的精度,你可以訪問 printf 這個問題或者訪問這個cout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM