栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

第二章 printf 语句与C++中的判断结构

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第二章 printf 语句与C++中的判断结构

第二章
  • 一.printf()输出格式
  • 二.if语句
  • 三.条件表达式

一.printf()输出格式

使用printf最好添加头文件 #include

#include
#include

using namespace std;

int main()
{
	printf("hello, world!");
	return 0;	
} 
  1. int float double char等类型的输出格式:
类型输出格式
int%d
float%f 默认保留6位小数
double%lf,默认保留6位小数
char%c,回车也是字符‘n’表示
#include
#include

using namespace std;

int main()
{
	int a = 3;
	float b = 3.12345678;
	double c = 3.12345678;
	char d = 'a';
	printf("%dn",a);
	printf("%fn",b);
	printf("%lfn",c);
	printf("%cn",d);
	return 0;
}
  1. 扩展功能
  • float double等输出保留若干位小数时用:%.nf,%nlf
#include
#include

using namespace std;

int main()
{
	double a=3.14159;
	float b=3.14159;
	printf("%.3lfn",a);//保留三位 
	printf("%.2fn",b);//保留两位 
	return 0;
}
  • 最小数字宽度:
    a: %8.3f,表示这个浮点数最小宽度为8,保留三位小数,当宽度不足在前面补上空格
#include
#include

using namespace std;

int main()
{
	int a=1;
	printf("%3d",a);//前面补上两个空格 
	return 0;
}

b:%-8.3f注意这里添了一个负号,表示最小宽度为8,保留三位小数,当宽度不足在后面补上空格

#include
#include

using namespace std;

int main()
{
	int a=1;
	printf("%-5d!",a);//往左补空格 
	return 0;
}

c:%08.3f,表示最小宽度为8,保留3位小数,当宽度不足时在前面补上0

#include
#include

using namespace std;

int main()
{
	int a=1;
	printf("%05d!",a);//往左补空格 
	return 0;
}
二.if语句
  1. 基本if-else语句
    当条件成立时候,执行某些语句,否则执行另一些语句
#include
#include

using namespace std;

int main()
{
	int a;
	cin >> a;
	if (a>5)
	{
		printf("%d大于5",a); 
	}
	else
	{
		printf("%d小于等于5",a);	
	} 
	return 0;
}
  1. 当if后面只有一条语句时,可以省略
#include
#include

using namespace std;

int main()
{
	int a;
	printf("正哥帅不帅,帅选1,非常帅选2n");
	scanf("%d",&a);
	if (a==1) printf("正哥好帅");
	else if (a==2) printf("正哥非常帅");
	else printf("你真帅"); 
	return 0;
}
  1. if-else语句内部也可以是if-else语句
#include
#include

using namespace std;

int main()
{
	int a;
	cin>>a;
	if(a>5)
	{
		if(a>6) printf("%d大于6",a);
		else printf("%d小于6,大于5",a); 
	}
	else
	{
		printf("%d小与5",a);
	}
	return 0;
}

4.常用的比较运算符

比较符含义
>大于
<小于
>=大于等于
<=小于等于
==等于
!=不等于
三.条件表达式
运算含义
&&
||
+=sum+=i,sum先加 i 后赋值给sum
-=sum-=i,sum先减 i 后赋值给sum
*=sum*=i,sum先乘 i 后赋值给sum
/=sum/=i,sum先加除i 后赋值给sum
%=sum%=i,sum先除i取余 后赋值给sum
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/676029.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号