c++基础篇2(数据类型)

本文精选了C++编程中的实用技巧,包括字符型数据运算、实数与零的精确比较、标准输入输出流的使用、字符输出及控制打印格式的方法。通过具体代码示例,深入浅出地讲解了如何在C++中高效处理各种数据类型。

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

1.字符型数据进行运算

#include <iostream>
//using namespace std;
void main()
{
	char ch1, ch2;
	ch1 = 'a';
	ch2 = 'A';
	printf("ch1=%d\n",ch1);
	printf("ch2=%d\n",ch2);
	printf("ch1=%c,ch2=%c\n", ch1 - 32, ch2 + 32);
	system("pause");
}

结果:
在这里插入图片描述
实现了A与a的互换

2实数与零比较(更可靠的一种方法)

#include <iostream>
void main()
{
	float eps = 0.0000001;
	float fvar = 0.00001;
		if (fvar >= -eps&&fvar <= eps)
			printf("zero\n");
		else
			printf("不是零\n");
	system("pause");
}

结果:
在这里插入图片描述

3cin和cout

#include <iostream>
using namespace std;
void main()
{
	int input;
	cout << "please input a number" << endl;       //endl是换行
	cin >> input;
	cout << "the number is" << input << endl;
	system("pause");
}

结果:
在这里插入图片描述

4简单输出字符

#include <iostream>
using namespace std;
void main()
{
	int i=1;
	cout << i << endl;
	cout << "I love you"  << endl;
	system("pause");
}

结果:
在这里插入图片描述

5控制打印格式程序

#include <iostream>
#include <iomanip>
using namespace std;
void main()
{
	double a = 123.123456789123;
	cout << a << endl;                       //默认精度为6
	cout << setprecision(9) << a << endl;    //精度设为9
	cout << setprecision(6) << a << endl;    //恢复精度
	cout << setiosflags(ios::fixed);
	cout << setiosflags(ios::fixed)<< setprecision(8) << a << endl; //小数点后八位
	//cout << setiosflags(ios::scientific)<< a << endl;
	//cout << setiosflags(ios::scientific)<<setprecision(4) << a << endl;//有疑问
	system("pause");
}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

萌萌松

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

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

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

打赏作者

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

抵扣说明:

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

余额充值