【问题标题】:How to declare complex numbers without their fields getting mixed up? [duplicate]如何在不混淆字段的情况下声明复数? [复制]
【发布时间】:2023-03-30 07:09:01
【问题描述】:

我尝试创建复数,但无论出于何种原因,它们总是出现实部具有虚值而虚部归零。 例如,我希望这个小测试应用程序能够打印 (1,2) 的多个实例,但无论我如何尝试接近它,我得到的都是 (2,0)。

#include "stdafx.h"
#include <complex>
#include <iostream>
using namespace std;
int main()
{
    std::complex<double>** complexdouble_c;
    complexdouble_c = new std::complex<double>*[5];
    for (int i = 0; i < 5; ++i)
        complexdouble_c[i] = new std::complex<double>[2];

    for (int i = 0; i < 5 && i < 15; i++) {
        for (int j = 0; j < 2 && j < 15; j++) {
                double real = 1;
                double imag = 2;
                complexdouble_c[i][j] = (real, imag);
            }
        }
    for (int i = 0; i < 5 && i < 15; i++) {
        for (int j = 0; j < 2 && j < 15; j++) {
            std::cout << complexdouble_c[i][j];
        }
        std::cout << "\n";
    }
    std::complex<double> complexdouble;
    double real = 1.0;
    double imag = 2.0;
    complexdouble = (real, imag);
    std::cout << complexdouble;
    std::cout << complexdouble.real();
    std::cout << complexdouble.imag();
    getchar();
}

【问题讨论】:

  • 您可能应该重新考虑使用 C++ 编写 Java 代码的倾向。这个程序没有什么需要使用new。所有这些都会造成大量内存泄漏,以及大量滥用或不当使用指针的机会,从而导致未定义的行为和崩溃。
  • @Sam Varshavchik 如果我要尝试制作一个二维数组,我会为它保留内存。 std::complex 有什么让它与众不同的地方吗? (另外我也不是很懂 Java。我只是简单地尝试做一个虚拟示例,我将尝试将其转换为动态数组。)
  • 出现错误的机会更少,并且没有需要处理的内存泄漏。而且这种方法实际上比单个二维数组或std::array浪费更多的内存。
  • complexdouble = (real, imag); 不会做你认为的那样。 (real, imag) 的意思是“评估 real 并将其丢弃,然后评估 imag 并返回其值”。有关更详细的说明,以及分配复数的正确方法列表,请参阅副本。

标签: c++


【解决方案1】:

以这种格式声明。这将给出以下输出

std::complex<double> c(1, 2);
// 1 + 2i

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2017-10-28
    • 2012-08-12
    • 2022-01-16
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2016-10-13
    • 2018-01-18
    相关资源
    最近更新 更多