为什么错误总是返回“变量具有不完整的类型无效”?

问题描述

我正在尝试编写代码,以解决库仑定律方程中两个带电粒子之间的作用力(使用空隙),并且我不断 错误:变量的类型“ void”不完整。 该代码应测量r = 1,然后循环(每次将3加到r),并在r

int main() {
float Q_one;
float Q_two;
int rad = 1;
double const k = 8990000000;
cout << "Enter the charge of particle 1." << endl;
cin >> Q_one;
cout << "Enter the charge of particle 2." << endl;
cin >> Q_two;
void force (float Q_one,float Q_two,int rad);
void force = ((k * ((Q_one * .000001) * (Q_two * .000001))) / (rad * rad));
while (rad <= 60) {
    {
        force (Q_one,Q_two,rad);
        cout << "Radius " << (rad) << " ";
        cout << "Force " << (force) << endl;
        rad += 3;
    }
}

}

我尝试过重新排列这种多种方式,并更改了“力”的定义方式,但似乎无济于事。关于如何解决此问题的任何想法?

解决方法

我不确定您要做什么。

解决了一些错误后,我得到了:

#include <iostream>
#include <type_traits>
#include <vector>
using namespace std;
int main() {
    float Q_one;
    float Q_two;
    int rad = 1;
    double const k = 8990000000;
    cout << "Enter the charge of particle 1." << endl;
    cin >> Q_one;
    cout << "Enter the charge of particle 2." << endl;
    cin >> Q_two;
    auto force = [k](float Q_one,float Q_two,int rad) { return (k * Q_one * .000001 * Q_two * .000001) / (rad * rad); };
    while (rad <= 60) 
        {
            auto result = force (Q_one,Q_two,rad);
            cout << "Radius " << (rad) << " ";
            cout << "Force " << (result) << endl;
            rad += 3;
        }
}

演示:wandbox

看起来像你想要的吗?

,

我假设您正在尝试创建一个函数来计算力。例如,您可以将其设为lambda函数:

F

然后在循环中调用它,并将其分配给 while (rad <= 60) { double F = force(Q_one,rad); cout << "Radius " << (rad) << " "; cout << "Force " << (F) << endl; rad += 3; } ,如下所示:

{{1}}