【发布时间】:2020-12-11 02:52:58
【问题描述】:
我必须为一个函数编写代码,该函数使用循环来计算从 1 到 n 的所有整数的总和。 我还需要做一个时间分析,把每一个基本操作(比如赋值和++)算作一个操作。我需要帮助来了解如何计算每个基本操作。 int computeSume(int n) 是一步,即C1吗? for循环是多个步骤吗? 请帮忙解释一下。谢谢。
#include <iostream>
using namespace std;
//Create a function that uses a loop to compute the sum of all integers from 1 to n.
//Create Function
int computeSum(int n)
{
//create sum variable
int sum = 0;
//create for loop
// i must be <= to n so it will count all integers and not cut the last int off.
for (int i = 0; i <= n; i++)
{
sum = sum + i;
}
//return statement
return sum;
}
//Main Method
int main()
{
//Input varibale
int n;
//Create user prompt
cout << "Enter a value: " << endl;
cin >> n;
cout << "The sum of all integer from 1 to " << n << " is " << computeSum(n) << "." << endl;
return 0;
}
【问题讨论】:
-
int op_count = 0;每次做基本操作,就做++op_count; -
见
std::accumulate。