请改进这段代码:int main() { int n; cin >> n; vector<int> result; generate_half_set(n, n, result); cout << "求解结果:{"; for (int i = 0; i < result.size(); i++) { cout << result[i]; if (i != result.size() - 1) { cout << " "; } } cout << "} n=" << n << "时半数集的个数:" << result.size() << endl; return 0; }
时间: 2024-01-25 14:04:44 浏览: 90
以下是改进后的代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
void generate_half_set(int n, int cur, vector<int>& result) {
result.push_back(cur);
for (int i = 1; i <= cur / 2; i++) {
generate_half_set(n, cur - i, result);
}
}
int main() {
int n;
cout << "请输入一个自然数n:";
cin >> n;
vector<int> result;
generate_half_set(n, n, result);
cout << "半数集:{";
for (int i = 0; i < result.size(); i++) {
cout << result[i];
if (i != result.size() - 1) {
cout << " ";
}
}
cout << "},n=" << n << "时半数集的个数:" << result.size() << endl;
return 0;
}
```
改进说明:
1. 添加了输入提示,让用户知道需要输入什么;
2. 将vector<int> result作为引用传递,避免了拷贝,提高了效率;
3. 将输出结果的格式改为更加美观的形式,易于阅读。
阅读全文