【问题标题】:C++ Err: 'Called object type 'int' is not a function or function pointer'C++ 错误:'调用的对象类型'int'不是函数或函数指针'
【发布时间】:2015-10-01 16:00:40
【问题描述】:

我正在尝试用 C++ 编写一个二次方程计算器,但我一直遇到这个错误。看看你是否能找出原因: (错误发生在 'g =' 行)

#include <cmath>
#include <iostream>
using namespace std;
int main(){
    int a,b,c,d,e,f,g;
    cout<<"Enter 'A' value:";
    cin>>a;
    cout<<"Enter'B' value:";
    cin>>b;
    cout<<"Enter 'C' value:";
    cin>>c;
    e = ((b * b) - (4 * (a*c)));
    d = sqrt(e);
    f = ((-b) + d) / (2 * a);
    g = ((-b) - d) / (2 * a);
    if(d > 0){
        cout<<"One solution is: "<<f<<endl;
        cout<<"The other solution is: "<< g <<endl;
    }
    else if(d == 0){
        cout<<"Your 1 solution is: "<< f <<endl;
    }
    else{
        cout<<"No real solutions!"<<endl;
    }
}

感谢任何帮助!

【问题讨论】:

  • 您应该查看整数除法和浮点除法之间的区别。你真的要使用整数除法吗?
  • 顺便说一句,square root function 返回一个浮点值,而不是整数。
  • @ThomasMatthews 不,你没有。如果控制从main 流出而没有return 语句,则暗示retun 0
  • 我在 Cygwin for Windows 7 上使用 g++ 版本 4.9.2 时没有出现编译错误。
  • Works for me。我猜在你的真实代码中,你忘记了/ 字符。

标签: c++ function int


【解决方案1】:

平方根函数会返回浮点值,所以你应该使用像double这样的浮点变量来存储结果。

#include <cmath>
#include <iostream>
using namespace std;
int main(){
    int a,b,c,e;
    double d,f,g;
    cout<<"Enter 'A' value:";
    cin>>a;
    cout<<"Enter'B' value:";
    cin>>b;
    cout<<"Enter 'C' value:";
    cin>>c;
    e = ((b * b) - (4 * (a*c)));
    d = sqrt(e);
    f = ((-b) + d) / (2 * a);
    g = ((-b) - d) / (2 * a);
    if(d > 0){
        cout<<"One solution is: "<<f<<endl;
        cout<<"The other solution is: "<< g <<endl;
    }
    else if(d == 0){
        cout<<"Your 1 solution is: "<< f <<endl;
    }
    else{
        cout<<"No real solutions!"<<endl;
    }
}

【讨论】:

  • 这段代码和O.P的代码有什么区别?为什么你没有解释就发布代码?
  • @Thomas 我已经添加了。
  • 虽然这可能是正确的,但仅靠代码并不是一个好的答案。请解释问题是什么,以及为什么这是解决方案,因此 A) OP 了解底层逻辑并可以自己解决这个问题和类似问题,B) 其他读者可以理解答案并将其应用到他们的有类似(但不相同)的问题。
  • 啊,好吧,你明白了。 (我发布后它刷新了。)
  • 我尝试实施您建议的更改,但现在 'e =' 行上出现了同样的错误。
【解决方案2】:

问题是平方根函数返回一个浮点小数,而您正试图将它与一个整数相结合。例如,1 - 2.0。这两个值都必须是浮点小数,因此您应该在第 5 行将“int”更改为“double”。

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多