4 条题解

  • 3
    @ 2023-6-22 20:13:20

    本题有四种思路,我不像楼上那么,所以就一一写出来了😄 (Oh,no!我的手好酸!!!)

    思路一:用for循环求解

    CodeCode

    #include<bits/stdc++.h>//万能头文件
    
    using namespace std;
    
    int main(){
    	int n,ans=0;//ans用来存储最后的总数(记得初始化)
    	cin>>n;
    	for(int i=1;i<=n;i++){
    		ans+=i;//叠加,也可以写成ans=ans+i;
    	}
    	cout<<ans;//输出
    	return 0;
    }
    

    思路二:用while循环求解

    CodeCode

    #include<bits/stdc++.h>
    
    using namespace std;
    
    int main(){
    	int n,ans=0;
    	cin>>n;
    	while(n>0){//while循环过程
    		ans+=n;
    		n--;
    	}
    	cout<<ans;
    	return 0;
    }
    

    思路三:用公式求解,公式为n*(n+1)/2

    CodeCode

    #include<bits/stdc++.h>
    
    using namespace std;
    
    int main(){
    	int n,ans=0;
    	cin>>n;
    	cout<<n*(n+1)/2;//套公式,直接输出
    	return 0;
    }
    

    思路四:用递归求解

    CodeCode

    #include<bits/stdc++.h>
    
    using namespace std;
    int f(int x){//递归函数
    	if(x==1){
    		return 1;
    	}
    	return x+f(x-1);
    }
    int main(){
    	int n;
    	cin>>n;
    	cout<<f(n);
    	return 0;
    }
    

    看在我打了4种方法的份上,您就发发慈悲点个赞吧❤️❤️❤️ ,我会感谢您的大恩大德的🎉️

    信息

    ID
    1105
    时间
    1000ms
    内存
    256MiB
    难度
    3
    标签
    递交数
    175
    已通过
    93
    上传者