|
发表于 2023-11-19 16:25:46
|
显示全部楼层
- ++
- #include <iostream>
- #include <string>
- #include <cmath>
- #include <iomanip>
- double calculateSeverity(const std::string& num) {
- int count = 0;
- int length = num.length();
- double severity = 0.0;
- for (char digit : num) {
- if (digit == '2') {
- count++;
- }
- }
- if (num[0] == '-') {
- severity += 0.5;
- if ((num[length - 1] - '0') % 2 == 0) {
- severity += 1.0;
- }
- severity *= 1.5 * count / length * 100;
- } else {
- if ((num[length - 1] - '0') % 2 == 0) {
- severity += 1.0;
- }
- severity = count / static_cast<double>(length) * severity * 100;
- }
- return severity;
- }
- int main() {
- std::string input;
- std::cin >> input;
- double severity = calculateSeverity(input);
- std::cout << std::fixed << std::setprecision(2) << severity << "%" << std::endl;
- return 0;
- }
复制代码
上面是一个修改后的 C++ 程序,用于计算给定整数的“犯二程度”。程序在 calculateSeverity 函数中计算了“犯二程度”的值,并在 main 函数中进行输入和输出处理。
主要修改包括:
1. 使用 <iomanip> 头文件设置输出的小数点精度为两位。
2. 将计算“犯二程度”的逻辑封装到单独的函数 calculateSeverity 中,提高代码的可读性和模块化程度。
3. 在 main 函数中调用 calculateSeverity 函数来计算结果,并输出结果。
希望以上代码对你有所帮助。如果还有其他问题,请随时向我提问。 |
|