zoukankan      html  css  js  c++  java
  • [SP1] TEST

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

    老规矩,先看题目。

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


    代码

    一、递归法

    (注释版)

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

    (无注释版)

    1 #include<bits/stdc++.h>
    2 using namespace std;
    3 int main(){
    4     int a;
    5     cin>>a;
    6     if(a!=42) cout<<a<<endl,main();
    7     return 0;
    8 }

    二、while输入法

    (注释版)

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

    (无注释版)

    1 #include<bits/stdc++.h>
    2 using namespace std;
    3 int main(){
    4     int a;
    5     while(cin>>a,a!=42)
    6         cout<<a<<endl;
    7     return 0;
    8 }

    总结

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

  • 相关阅读:
    Best Time to Buy and Sell Stock
    Remove Nth Node From End of List
    Unique Paths
    Swap Nodes in Pairs
    Convert Sorted Array to Binary Search Tree
    Populating Next Right Pointers in Each Node
    Maximum Subarray
    Climbing Stairs
    Unique Binary Search Trees
    Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/integricode26/p/SP1-test-life-the-universe-and-everything-solution.html
Copyright © 2011-2022 走看看