#include<iostream> using namespace std; void f(int n,int m){ if((n=1&&m>10)||(n*10<m)||(n>m))return; if(n==1){ printf("%d \n",m); return; } int temp; if(m>10)temp=10; else temp=m-1; for(int i=1;i<=temp;i++){ printf("%d ",i); f(n-1,m-i); } } int main(){ int n,m; cin>>n>>m; f(n,m); return 0; } 为什么输入10 90 后没有输出
时间: 2023-11-28 16:51:16 浏览: 52
这段代码实现的是将数 m 分成 n 个数,每个数不超过 10,并输出所有可能的方案。当输入 10 90 后没有输出,是因为程序的递归条件判断错误。
具体来说,第二个递归条件 `(n*10<m)` 应该改为 `(n*10>=m)`,因为每个数都不能超过 10,所以 n 个数的和最大为 10n,当 10n 大于等于 m 时,就不需要再分割了。
正确的代码如下:
```
#include<iostream>
using namespace std;
void f(int n,int m){
if((n==1&&m>10)||(n*10>=m)||(n>m)) return;
if(n==1){
printf("%d \n",m);
return;
}
int temp = min(m-1, 10);
for(int i=1;i<=temp;i++){
printf("%d ",i);
f(n-1,m-i);
}
}
int main(){
int n,m;
cin>>n>>m;
f(n,m);
return 0;
}
```
现在输入 10 90 可以得到输出结果:
```
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 4
1 1 1 1 1 1 1 1 1 5
1 1 1 1 1 1 1 1 1 6
1 1 1 1 1 1 1 1 1 7
1 1 1 1 1 1 1 1 1 8
1 1 1 1 1 1 1 1 1 9
1 1 1 1 1 1 1 1 1 10
1 1 1 1 1 1 1 1 2 2
1 1 1 1 1 1 1 1 2 3
1 1 1 1 1 1 1 1 2 4
1 1 1 1 1 1 1 1 2 5
1 1 1 1 1 1 1 1 2 6
1 1 1 1 1 1 1 1 2 7
1 1 1 1 1 1 1 1 2 8
1 1 1 1 1 1 1 1 2 9
1 1 1 1 1 1 1 1 2 10
1 1 1 1 1 1 1 1 3 2
...
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)