为什么将while循环语句里的“res=0”改为“int res=0”则结果不同?

问题

img

输入

img

疑问
当while语句里写为res=0,则输出正确结果

img

但当while语句里写为int res=0;,则输出错误结果

img


在执行while语句时,不都是从上向下执行吗?并且都是让res=0,为什么会有不一样的结果?是因为在main里面,输出的默认为局部变量res吗

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>

using namespace std;

int res;
int m,n;

void dfs(int t,int start,int state)
{
    if(state==n&&t==0) res++;
    
    if(state>=n) return;
    
    for(int i=start;i<=t;i++)
        dfs(t-i,i,state+1);
}

int main()
{
    int t;
    cin>>t;
    
    while(t--)
    {
        cin>>m>>n;
        
        res=0;
        dfs(m,0,0);
        
        cout<<res<<endl;
    }
    
    return 0;
}

int res = 0 就是在while函数内部重新生成了一个res变量了,和函数外的res就没有关联了

因为这里的res是个全局变量,和函数中的res是同一个变量。如果你写成int res,那么main里的res就是本地局部变量,和函数里的res是两个变量。这样函数里res修改后,本地的res并不会修改,自然不对了啊