[英]In Cpp for is not working properly from the function
我需要做這個練習,使用 struct 並在 struct 中包含 function 來進行計算,但由於某種原因,它不起作用。 我建議您檢查圖像以獲得更好的想法。
#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;
}
您沒有遵循圖像中的公式。 改用這個:
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++)
表示i
初始化為 1,而i>=n
執行循環,然后 inc i
。 所以當n
大於1時,它永遠不會進入循環。 也許你想要for (int i = 1; i <= n+1; i++)
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.