【捡起C++】循环和关系表达式

//求阶乘
#include <iostream>
const int ArSize = 16;
int main(){
	long long  factorials[ArSize];
	factorials[0] = factorials[1] = 1LL;
	for (int i = 2; i < ArSize; i++){
		factorials[i] = i * factorials[i - 1];
	}
	for (int i = 0; i < ArSize; i++){
		std::cout << i << "! = " << factorials[i] << std::endl;
	}
	return 0;
}

​ 如果在一个语句块中声明一个变量,而外部语句块中也有一个这种名称的变量,情况将如何呢?在声明位置到内部语句块结束的范围之前,新变量将隐藏旧变量;然后旧变量再次可见

#include <iostream>

int main(){
	using std::cout;
	using std::endl;
	int x = 20;	        //original x
	{					//block starts
		cout << x << endl;                //use original x
		int x = 100;				//new x
		cout << x << endl;				//use new x
					           
	}					//block ends
	cout << x << endl;  //use original x
	return 0;
}
逗号运算符花絮

​ 在所有的运算符中,逗号运算符的优先级是最低的。

cata = 20, 240;

​ 被解释为:

(cats = 17), 240;

​ 也就是,cats将设置为17,240不起作用。

cats = (17, 240)//cats被设置为240,逗号右侧的表达式值
#include <iostream>
#include <cstring>
int main(){
	using namespace std;
	char word[5] = "?ate";
	for (char i = 'a'; strcmp(word, "mate") != 0; i++){
		cout << word << endl;
		word[0] = i;
	}
	cout << "After loop ends, word is " << word << endl;
	return 0;
}
基于范围的for循环(C++11)

​ C++11新增了一种循环:基于范围(range-based)的for循环。

double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};
for(double x : prices){
    std::cout << x << std::endl;
}

​ 其中,x最初表示数组prices的第一个元素。

​ 要修改数组的元素,需要用不同的循环变量语法

for(double& x : prices){
    x = x * 0.80;
}

​ 符号&表明 x 是一个引用变量。

​ 还可结合使用基于范围的for循环和初始化列表:

for(int x : {3, 5, 2, 8, 6}){
    cout << x << " ";
}
cout << '\n';
#include <iostream>

const int Cities = 5;
const int Years = 4;
int main() {
	using namespace std;
	const char* cities[Cities] = {
		"AAA",
		"BBB",
		"CCC",
		"DDD",
		"EEE"
	};
	int maxtemps[Years][Cities] = {
		{1, 2, 3, 4, 5},
		{6, 7, 8, 9, 10},
		{6, 7, 8, 9, 10},
		{11, 12, 13, 14, 15},
	};
	for (int city = 0; city < Cities; city++) {
		cout << cities[city] << ":\t";
		for (int  year = 0; year < Years; year++){
			cout << maxtemps[year][city] << "\t";
		}
		cout << endl;
	}
	return 0;

}

​ 许多程序都逐字节地读取文本输入或文本文件,istream类提供了多种可完成这种工作的方法。如果ch是一个 char变量,则下面的语句将输入中的下一个字符读入到ch中:

cin >> ch;

​ 然而,它将忽略空格、换行符和制表符。下面的成员函数调用读取输入中的下一个字符(而不管该字符是什么)并将其存储到ch中:

cin.get(ch);

​ 成员函数调用 **cin.get()**返回下一个输入字符——包括空格、换行符和制表符,因此可以这样使用它:

ch = cin.get();

​ cin.get(char) 成员函数调用通过返回转换为false的 bool值 来指出已达到 EOF,而 cin.get()函数则通过返回EOF值来指出已达到EOF,EOF是在文件iostream中定义的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值