【问题标题】:Loop and function in Integration Program (C++) [closed]集成程序(C++)中的循环和函数[关闭]
【发布时间】:2013-01-21 06:16:40
【问题描述】:

我正在开发一个使用 [right] 矩形和的集成程序。我使用起始边界作为 a=1,使用“n”作为矩形的数量,使用“inc”作为增加 z 的增量。这是我到目前为止的代码:

#include <iostream>
#include <cmath>

using std::cout;
using std::endl;
using std::cin;

int main(){

    int n;
    float b;
    float z;
    z=((b-1)/n);
    float inc;
    float new_sum;
    float sum;
    int decision;


    cout << "Would you like to calculate an area? " << endl;
    cout << "Enter 1 for yes, 0 for no: " << endl;
    cin >> decision;

    cout << "Please enter the number of rectangles you would like to use: " << endl;
    cin >> n;
    cout << "Please enter the upper bound of integration: " << endl;
    cin >> b;

    for (inc=0; inc < b; inc++){
        new_sum=z*(f(1+(inc*z)));
        sum=sum+new_sum;
    }

    cout << sum << endl;

return 0;

}

我有两个问题:

  1. 我该如何使用函数 f(x)=x^5 + 10?我不确定在 for 循环中应该如何输入和格式化。

  2. 如何循环第一个问题序列(您想计算面积吗?),使用 for 循环,重复直到用户输入 1 表示是(我知道如何使用 while 循环执行此操作,但想知道如何使用 for 循环来完成?)

【问题讨论】:

  • for 循环非常适合您知道要循环多少次的情况。 for(;&lt;cond&gt;;)while(&lt;cond&gt;) 相同,但更令人困惑..
  • 你试过pow (x,5)for(;&lt;condition&gt;;)吗?

标签: c++ loops integration


【解决方案1】:

我如何在其中使用函数 f(x)=x^5 + 10?我不确定它应该如何在 for 循环中输入和格式化。

float f( float x ) {
    return pow( x, 5 ) + 10; // maybe x * x * x * x * x + 10
}

在函数 main 定义之前添加这一行。

我如何循环第一个问题序列(你想计算一个面积吗?),使用 for 循环,重复直到用户输入 1 表示是(我知道如何使用 while 循环来做到这一点,但是想知道如何使用 for 循环来完成?)

for (;;) {
    cout << "Would you like to calculate an area? " << endl;
    cout << "Enter 1 for yes, 0 for no: " << endl;
    cin >> decision;
    if ( decision != 1 ) // or if ( decision == 0 )
    {
        break;
    }

    cout << "Please enter the number of rectangles you would like to use: " << endl;
    cin >> n;
    cout << "Please enter the upper bound of integration: " << endl;
    cin >> b;

    for (inc=0; inc < b; inc++){
        new_sum=z*(f(1+(inc*z)));
        sum=sum+new_sum;
    }

    cout << sum << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2013-12-17
    • 2018-03-07
    • 2023-02-13
    • 1970-01-01
    相关资源
    最近更新 更多