一、printf 输出格式
注意:使用printf 时最好添加头文件 #include 。
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
printf("Hello World!");
return 0;
}
1.Int、float、double、char等类型的输出格式:
(1)Int:%d
(2)Float: %f, 默认保留6位小数
(3)Double: %lf, 默认保留6位小数
(4)Char: %c, 回车也是一个字符,用’\n’表示
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a=3;
float b = 3.12345678;
double c = 3.12345678;
char d = 'y';
printf("%d\n", a);
printf("%f\n", b);
printf("%lf\n", c);
printf("%c\n", d);
return 0;
}
2.所有输出的变量均可包含在一个字符串中:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a=3;
float b = 3.12345678;
double c = 3.12345678;
char d = 'y';
printf("int a = %d, float b = %f\n, double c = %lf, char d = %c\n",a,b,c,d);
return 0;
}
练习:输入一个字符,用这个字符输出一个菱形:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char c;
cin >> c;
printf(" %c \n", c);
printf(" %c%c%c\n", c,c,c);
printf("%c%c%c%c\n", c,c,c,c);
printf(" %c%c%c\n", c,c,c);
printf(" %c \n", c);
return 0;
}
练习:输入一个整数,表示时间,单位是秒。输出一个字符串,用”时:分:秒”的形式表示这个时间。
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int t;
cin>>t;
int hours = t / 3600;
int minutes = t % 3600 / 60;
int seconds = t % 60;