[SP1] TEST - Life, the Universe, and Everything.题解

本文通过一个具体的编程题目,介绍了在C++中使用递归和while循环处理连续输入的方法。通过对比两种解决方案,帮助读者理解递归调用和逗号表达式的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个红SP题过水,入门coders可自行食用!

老规矩,先看题目。

显然题目不难理解,就是让我们在看到424242之前,输出所有输入的数字。
这题我们讲解两种做法:一个是递归,一个是whilewhilewhile的不断输入用法!


代码

一、递归法
(注释版)
#include<bits/stdc++.h>//万能头文件
using namespace std;
int main(){//好习惯,程序从主函数读起
    int a;
    cin>>a;
    if(a!=42) cout<<a<<endl,main();//当a不等于42时,输出a,并无限次递归调用主函数
    return 0;//返回值0,程序正常退出
}
(无注释版)
#include<bits/stdc++.h>
using namespace std;
int main(){
    int a;
    cin>>a;
    if(a!=42) cout<<a<<endl,main();
    return 0;
}

二、whilewhilewhile输入法
(注释版)
#include<bits/stdc++.h>//万能头文件
using namespace std;
int main(){//好习惯,程序从主函数读起
    int a;
    while(cin>>a,a!=42)
    /*while(cin>>a)表示不断输入a,直到程序结束即EOF(End of File)
    其中用逗号连接两个不同表达式,类似于逻辑且&&*/
        cout<<a<<endl;
    return 0;
}
(无注释版)
#include<bits/stdc++.h>
using namespace std;
int main(){
    int a;
    while(cin>>a,a!=42)
        cout<<a<<endl;
    return 0;
}

总结

1. 不断递归调用mainmainmain(或其他函数)能达到反复执行一内容的效果。
2. while(cin>>a)while(cin>>a)while(cin>>a): 不断输入aaa直至无可读取信息。
3. while(,)while( , )while(,): 用逗号表达式连接不同的表达式,类似于逻辑且&&。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值