if,while,std::cin,std::cout用法练习
2018-01-27 22:24
232 查看
实例:统计输入值连续出现的次数
如果我们输入如下内容:
42 42 42 42 42 55 55
则输出应该是:
input 42 5 times !
input 55 2 times !
分析:
输入42,lastVal为输入值42,count设置为1,while方法不走;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为2;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为3;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为4;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为5;
输入55,inputVal为输入值55,inputVal==lastVal不成立进入else里,打印“input 42 5 times !”,重新赋值给lastVal为55,count重置为1;
输入55,inputVal为输入值55,inputVal==lastVal成立,count加1值为2;
#include <iostream> int main() { int lastVal = 0,inputVal = 0; if(std::cin>>lastVal)//第一次输入值赋值给lastVal { int count = 1; while(std::cin>>inputVal)//第二次输入值赋值给inputVal { if(inputVal == lastVal)//上一次输入的值和这一次输入的值相等时 { ++count; }else{//不相等先打印之前相等的总共的次数,然后做个终结,最后重新记录 std::cout<<" input "<<lastVal<<" "<<count<<" times !"<<std::endl; lastVal = inputVal; count = 1; } } std::cout<<" input "<<lastVal<<" "<<count<<" times !"<<std::endl;//打印最后输入值的统计 } return 0; }
如果我们输入如下内容:
42 42 42 42 42 55 55
则输出应该是:
input 42 5 times !
input 55 2 times !
分析:
输入42,lastVal为输入值42,count设置为1,while方法不走;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为2;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为3;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为4;
输入42,inputVal为输入值42,inputVal==lastVal成立,count加1值为5;
输入55,inputVal为输入值55,inputVal==lastVal不成立进入else里,打印“input 42 5 times !”,重新赋值给lastVal为55,count重置为1;
输入55,inputVal为输入值55,inputVal==lastVal成立,count加1值为2;
相关文章推荐
- if,for,while用法及 练习
- if(cin) while(cin) 以及 while(cin>>x) 条件表达式中的 流对象cin 的用法
- C++中cin/cout的用法
- shell脚本练习一(if语句、case语句、for语句、while语句)
- std::find_if 用法
- C++输入cout与输出cin(详细用法)
- cin cout 用法
- android Monkeyrunner:Python语法知识学习(for,while,if用法实例)
- java的if-else和while用法
- std::cout、std::cin与cout.cin
- 输入输出cin,cout用法
- C++学习笔记(一):关于cin与while的配合用法
- expect语法基础: while、for 循环、if 语句的用法示例
- std count_if用法
- 2018-4-3 if while基本用法
- #define fun() do {a***; b***;} while(0)在if语句后的用法探讨
- expect语法基础: while、for 循环、if 语句的用法示例
- if/switch/while/do while/for/等循环及判断的简要用法案例
- 关于if (!cin)以及while (cin >> word)
- while练习之计算1到100的奇数和与continue用法