c++入门(2-2)-- 变量与基本类型

本文介绍了C++中变量的概念及使用方法,包括变量定义、初始化、作用域等,并通过实例演示了如何利用变量进行随机数生成及简单的口算测试程序。

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

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拉斐尔在读论文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值