【问题标题】:Error: Operand of '*' must be a pointer but has type "double" [duplicate]错误:“*”的操作数必须是指针,但类型为“double”[重复]
【发布时间】:2021-10-13 00:43:00
【问题描述】:

我知道以前有人问过这个问题,但那里的答案似乎与我遇到的问题无关。

这是我的代码

#include <iostream>

int main()
{
    double E;
    double R;
    double t;
    double C;
    
    std::cout << "This program will calculate the current flowing through an RC curcuit!\n\n";
    std::cout << "Please enter the power source voltage value in Volts: ";
    std::cin >> E;
    std::cout << "\n\n";
    std::cout << "Please enter the total resistance value in Ohms: ";
    std::cin >> R;
    std::cout << "\n\n";
    std::cout << "Please enter the time elapsed after the switch closed Seconds: ";
    std::cin >> t;
    std::cout << "\n\n";
    std::cout << "Please enter the total capacitance value in Farads: ";
    std::cin >> C;
    std::cout << "\n\n";
    double RC = R * C;
    double ER = E / R;
    double pow = -t / RC;
    double expo = 2.71828 ** pow; //this line is the problem...

    double I = ER * expo;
    std::cout << "The current flowing through this circuit is: " << I;

    return 0;
}

我真的不知道这意味着什么,尽管在 Google 上查找了它...有人可以解释一下,一般来说,如何避免这种类型的错误,而不仅仅是解决这个特定的实例吗?

【问题讨论】:

  • C++ 没有** 运算符。您需要 std::pow 函数来进行浮点取幂。请注意,这意味着 pow 不是您的变量名的好选择。
  • 错误的原因是因为没有**操作符,它被解析为2.71828 * *pow,其中*pow似乎试图应用一元*指针解引用操作符到pow。然后这会出错,因为 pow 不是指针。
  • 实际上,如果您想将e 提升为幂,请改用[std::exp(p)](https://en.cppreference.com/w/cpp/numeric/math/exp);比std::pow(2.71828, p)更准确。
  • 避免using namespace std;的好人。这使得在具有名为 pow 的变量的函数中使用 std::pow 函数变得不那么麻烦。
  • @user4581301 没有namespace std,也没有bits/stdc++.h。 OP 已经超过了许多 C++ 程序员。

标签: c++


【解决方案1】:

C++ 不像某些语言那样有** 运算符。您需要使用std::pow 函数来做指数,或者std::exp 用于将数学常数e 提高到幂的特殊情况。

#include <cmath>

...

double expo = std::exp(pow);

【讨论】:

  • 是的,谢谢你和 Nate 的意见...我想知道为什么它说 '*' 而不是 "**" lmao
  • 是的,C++ 将其解析为2.71828 * (*pow);,因此它期望pow 是一个指针。这不是最直观的东西,但不幸的是,这是语言理解它的唯一方式。
猜你喜欢
  • 2022-01-12
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多