下面我有练习写代码,不幸的是,这个代码不能正常工作,我在下面附上了正确的输出。 在此处输入图像说明
#下面我有练习写代码,不幸的是,这个代码不能正常工作,下面我附上了正确的输出。 在此处输入图像说明
#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;
}
代码中存在几个问题:
>
从未使用变量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