简体   繁体   English

在 Cpp 中,从 function 无法正常工作

[英]In Cpp for is not working properly from the function

I need to do this exercise, with struct and include the function in the struct to do the calculations, but for some reason, it's not working.我需要做这个练习,使用 struct 并在 struct 中包含 function 来进行计算,但由于某种原因,它不起作用。 I recommended you to check the image for a better idea.我建议您检查图像以获得更好的想法。 运动

#include <iostream>
using namespace std;
struct Alfa{
    double h,x,n,a;
    void shuma(){
        cout << "enter n: "; cin >> n;
        cout << "enter a: "; cin >> a;
        for (int i = 1; i >= n; i++){
            x = 2 * i + a;
        }
    };
};

int main() {
    Alfa alf;
    alf.shuma();
        alf.h = (alf.x / 2) + 3;

    cout <<  alf.h;

    return 0;
}

You are not following the formula in the image.您没有遵循图像中的公式。 Use this instead:改用这个:

double sum = 0;
for (int i = 1; i <= n + 1; i++) {
    if (i != 4) {
        sum += 2 * i + a;
    }
}
h = x / 2 + 3 * sum;

for (int i = 1; i >= n; i++) means i initiated to 1, while i>=n do the loop, then inc i . for (int i = 1; i >= n; i++)表示i初始化为 1,而i>=n执行循环,然后 inc i So when n is bigger then 1, it will never enter the loop.所以当n大于1时,它永远不会进入循环。 Maybe you want for (int i = 1; i <= n+1; i++) ?也许你想要for (int i = 1; i <= n+1; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM