c++入门(2-2)-- 变量与基本类型
作者:Raphael Song 如需转载,请注明出处。
The way to learn a new programming language is to write programs.
让我们开始!
如果你还没有接触过编程,想先体验一下编程的乐趣。请看我的c++入门(1)--输入输出,代码运行顺序及其控制。此文开始学习变量以及基本类型。
其中,c++入门(2-1)-- 变量与基本类型 着重讲基本类型。
这一篇,我将着重讲变量(P41-P49)。
变量(variables)
变量提供了能被我们的程序操作的带名字的存储器。C++中的每个变量都有一个类型,也必须指定类型,所以我们也将C++称为强类型语言。不同的类型会影响变量的内存大小和表现。
变量定义(variable definition)
初始化器(initializers)
默认初始化器(default initialization)
变量声明和定义(variable declaration and definition)
鉴别器(identifiers)
变量名的作用域(scope of a name)
嵌套作用域(nested scopes)
#include <iostream>
using namespace std;
int main (){
int i = 0;
for(int i = 0;i < 10 ; i=i+2){
cout << "hello world!" << endl;
cout << "i = " << i << endl;
if(i > 5) {
cout << "i > 5" << endl;
}
else {
cout << "i < 5" << endl;
}
}
while(i < 10){
i = 8848;
cout << "hello world!" << endl;
}
}
#include <iostream>
using namespace std;
int main (){
int i = 0;
for(int i = 0;i < 10 ; i=i+2){
cout << "hello world!" << endl;
}
cout << "i = " << i << endl;
if(i > 5) {
cout << "i > 5" << endl;
}
else {
cout << "i < 5" << endl;
}
while(i < 10){
i = 8848;
cout << "hello world!" << endl;
}
}
代码练习
随机数生成
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned)time(NULL));
for(int i=0;i<10;i++)
cout<<rand()<<' ';
return 0;
}
参考链接:c++生成随机数
改进口算测试程序
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned)time(NULL));
for(int i=0;i<10;i++){
int a = rand();
int b = rand();
cout << a << " + " << b << " = " ;
int c ;
cin >> c ;
if (c== a + b ){
cout <<"yes" << endl;
}else {
cout << "no" << endl;
}
}
return 0;
}
改进猜数程序
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
//猜小了猜大了
int main() {
int num;
srand((unsigned)time(NULL));
int a = rand();
//cout << a << endl;
cout << "我心里想了一个数字,你能猜到吗?试试看呗。" << endl;
for(int i = 0; i < 50;i++) {
cin >> num;
if(num == a) {
cout << "猜对了,我爱你!" << endl;
break;
} else {
if(i == 49){
cout << "很抱歉,你的十次机会已经用完。" << endl;
} else {
if (num > a){
cout << "不对,你猜大了。" << endl;
}
else {
cout << "不对,你猜小了。" << endl;
}
cout << "你还有" << 49 - i << "次机会" << endl;
}
}
}
return 0;
}