为什么我的方程给出错误必须有一个积分表达式或无作用域enun类型

Why is my equation giving Error must have an integral expression or unscoped enun type?

本文关键字:表达式 作用域 类型 enun 有一个 方程 我的 出错 错误 为什么      更新时间:2023-10-16

所以嘿伙计们,我想做一个简单的程序来学习函数,我遇到了这个错误,我从来没有有人能帮助我吗?

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;
float SphereVolume(float r);
int main() {
    /*
    Calculating a sphere.
    */
    float radius;
    cout << "Sphere Calc....n";
    cout << "tPlease Enter Radius of Sphere: ";
    cin << radius;
    SphereVolume(radius);
    return 0;
}

float SphereVolume(float r) {
    double const PI = 3.14159;
    float volume;
    volume = 4/3 * PI * r ^ 3; // error starts here.
    return volume;
}

我似乎无法理解为什么会发生这种情况,错误,开始时,我试图声明体积方程,它说错误??

volume = 4/3 * PI * r ^ 3; // error starts here.
4 / 3 is integer division -> 1  
r ^ 3  is r xor-ed with the integer 3. 

你不能xor浮点数。如果你想对一个浮点数求立方,最简单的方法就是将它乘以三次。

你有两个错误第一个可能会给你一堆错误代码

cin << radius;

正确的结构是:

cin >> radius;

第二个错误是你实际要求的:

volume = 4 / 3 * PI * r ^ 3;

^ -是对浮点类型不起作用的异或操作符。从4/3*PI*r得到的结果类型是double。你不能对它做任何事。
我想你实际上是在试图得到结果的3次方。在c++中,没有简单的操作符可以做到这一点。您可以像这样使用pow(..)函数:

volume = pow(4 / 3 * PI * r, 3);

请记住添加#include <cmath>才能使用该功能。