提问者:小点点

C++类和面向对象程序设计-请检查此代码-代码


下面我有练习写代码,不幸的是,这个代码不能正常工作,我在下面附上了正确的输出。 在此处输入图像说明

#下面我有练习写代码,不幸的是,这个代码不能正常工作,下面我附上了正确的输出。 在此处输入图像说明

#include <iostream>
#include <cmath>
using namespace std;

class Point {
    int x,y,z;
    public:
           Point(float a, float b, float c)
    {   x=a;
        y=b;
        z=c;
    }
    void print ()
    {
        cout<<"The x value is : " << x << endl;
        cout<<"The y value is : " << y << endl;
        cout<<"The z value is : " << z << endl;
    }
    
    inline float norm ()
    {
        float t = x*x + y*y + z*z;
        float s = sqrt(t);
        return t;
        
    }
    void negate ()
    {
        x= x * -1; y= y * -1; z= z * -1;
    }
};



int main ()
{
    Point (1,2,3);
    cout << "The function prints out: \n";
    A1.print ();
    cout<< "The result of norm is: " << A1.norm () << endl;
    A1.negate ();
    cout << "The result of negate: \n";
    A1.print ();
return 0;
}

共1个答案

匿名用户

代码中存在几个问题:

>

  • 从未使用变量float s=sqrt(t)

    是一个类的名称,它不是一个可以构造的对象。

    旁白:为什么使用名称空间std被认为是糟糕的实践?

    重新定义的代码:

    #include <iostream>
    #include <cmath>
    
    class Point {
        int x, y, z;
    
    public:
        Point(float a, float b, float c) {
            x = a;
            y = b;
            z = c;
        }
        void print() {
            std::cout << "The x value is : " << x << std::endl;
            std::cout << "The y value is : " << y << std::endl;
            std::cout << "The z value is : " << z << std::endl;
        }
    
        float norm() {
            float t = x * x + y * y + z * z;
            float s = sqrt(t);
            return s; // returning 's' instead of 't'
        }
        void negate() {
            x = x * -1;
            y = y * -1;
            z = z * -1;
        }
    };
    
    int main(void) {
        Point A1(1, 2, 3); // creating an object and then constructing
    
        std::cout << "The function prints out:" << std::endl;
        A1.print();
    
        std::cout << "The result of norm is: " << A1.norm() << std::endl;
        A1.negate();
    
        std::cout << "The result of negate:" << std::endl;
        A1.print();
    
        return 0;
    }
    

    然后您应该得到输出:

    The function prints out:
    The x value is : 1
    The y value is : 2
    The z value is : 3
    The result of norm is: 3.74166
    The result of negate:
    The x value is : -1
    The y value is : -2
    The z value is : -3
    

  • 相关问题


    MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|类|面向对象|程序设计|请|检查|代码|代码)' ORDER BY qid DESC LIMIT 20
    MySQL Error : Got error 'repetition-operator operand invalid' from regexp
    MySQL Errno : 1139
    Message : Got error 'repetition-operator operand invalid' from regexp
    Need Help?