继续收到错误"类型为float' and
的无效操作数int'二进制`运算符^'编译时我认为这是4/3的一个问题,但我不确定如何使它工作。我想我只是错过了一小部分代码,但花了一个多小时试图弄清楚
#include <iostream>
#define Pi 3.14159265359
using namespace std;
float SphereVol (float r)
{
float vol;
vol = ((4/3)*(Pi)*(r^3));
return vol;
}
int main()
{
float r, f = SphereVol(r);
for (r=0; r=4; r+(.2))
{
cout.precision(7);
cout << "Radius: " << r << " volume: " << SphereVol(r) << endl;
}
system("pause");
return 0;
}
我已经编辑了上面的代码,现在它正在显示正确的问题,并且由于某种原因,cout.precision(8)
使输出结果出现小数位不正确。它应该列出像
radius= 4.0000000 volume= .xxxxxxx
但是将整数留下十进制数。
#include <iostream>
#define Pi 3.1415926
using namespace std;
float SphereVol (float r)
{
float vol;
vol = ((4.0/3.0)*(Pi)*(r*r*r));
return vol;
}
int main()
{
float r;
float f = SphereVol(r);
for (r = 0; r <= 4; r += .2)
{
cout.precision(8);
cout << "Radius: " << r << " volume: " << SphereVol(r) << endl;
}
cout << endl;
system("pause");
return 0;
}
现在显示小数
示例:radius= 3.20000005
radius= 3.40000006
它应该显示为
Radius: 0.200000 volume: 0.033503
Radius: 0.400000 volume: 0.268082
Radius: 0.600000 volume: 0.904778
Radius: 0.800000 volume: 2.14466
Radius: 1.000000 volume: 4.18879
答案 0 :(得分:3)
在C ++(以及C语言中)中,^
运算符是仅适用于整数类型的逐位异或(XOR)运算符。
将数字提升为电力不是电力运营商。
您可以重写您的功能:
float SphereVol (float r)
{
return (float) (4.0 / 3.0 * Pi * r * r * r);
}
在你的代码中,表达式(4/3)将使用整数数学来完成,它会丢弃任何余数并将计算为1.在上面的代码中,我使用4.0和3.0来强制双精度浮点数学完成除法和乘法。然后我将该双精度结果转换为单个精度浮点数,以匹配函数的返回类型。
更一般地说,如果你#include <cmath>
http://en.cppreference.com/w/cpp/numeric/math/pow
确保float
具有足够的数学精度。您可能更愿意使用double
,而且更精确。
此外,您的循环语法错误。你写它的方式将导致无限循环。试试这个:
for (r = 0; r <= 4; r += 0.2)