分数累加程序怎么写

时间:2025-01-25 16:17:43 单机游戏

分数累加程序的编写可以通过多种方法实现,以下是几种不同的实现方式:

方法一:使用循环和符号变量

```cpp

include

using namespace std;

int main() {

int i = 1;

double sum = 0;

int sign = 1; // 用于控制正负号

while (i <= 19) {

double term = (double)i / (i + 2);

sum += sign * term;

sign *= -1; // 切换正负号

i += 2;

}

cout << "sum = " << sum << endl;

return 0;

}

```

方法二:使用do-while循环

```cpp

include

using namespace std;

int main() {

int i = 1;

double sum = 0;

int sign = 1; // 用于控制正负号

do {

double term = (double)i / (i + 2);

sum += sign * term;

sign *= -1; // 切换正负号

i += 2;

} while (i <= 19);

cout << "sum = " << sum << endl;

return 0;

}

```

方法三:使用C++标准库中的分数类

```cpp

include

include // for std::accumulate

include // for std::negate

int main() {

int start = 1;

int end = 19;

int step = 2;

std::vector fractions;

for (int i = start; i <= end; i += step) {

fractions.push_back(static_cast(i) / (i + 2));

}

double sum = std::accumulate(fractions.begin(), fractions.end(), 0.0, std::negate());

cout << "sum = " << sum << endl;

return 0;

}

```

方法四:使用输入输出重定向和字符串处理

```cpp

include

include

include

include

include

int main() {

std::string input;

std::getline(std::cin, input);

std::istringstream iss(input);

std::vector> fractions;

int numerator, denominator;

while (iss >> numerator >> denominator) {

fractions.emplace_back(numerator, denominator);

}

double sum = 0.0;

for (const auto& fraction : fractions) {

sum += fraction.first / fraction.second;

}

std::cout << "sum = " << sum << std::endl;

return 0;

}

```

这些方法各有优缺点,可以根据具体需求和编程习惯选择合适的方法。例如,方法一和方法二使用了简单的循环和符号变量,易于理解和实现;方法三利用了C++标准库中的`std::accumulate`和`std::negate`,代码更为简洁;方法四则通过输入输出重定向和字符串处理,适用于处理更复杂的输入格式。