上期参考答案,你做对了吗:
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a+b;
return 0;
}
这期讲的又是C语言的输入输出 printf 和 scnaf。
先赞后看,养成习惯!!!
首先,还是讲 printf ,它和 scanf 位于以下头文件(两个都有)
#include <cstdio>
#include <stdio.h>
想要使用printf,十分“简单”
printf("Text");
printf("Text&Format", Fill1, Fill2, ..., Filln);
这里还是举例子,因为作者烧了
#include <cstdio>
int main() {
printf("Hello everyone, I am a student. Nice to meet you! ");
return 0;
}
这时,你也烧了,“命名空间呢?”放进DEV-C++中却没有问题,而cout和cin却需要,为什么呢?其实,stdio.h 是C语言的库,C++照样能够使用。而在C语言中,标准的stdin(scanf)和stdout(printf)是没有作用域的。作用域是什么?这是函数利用的范围,如果不写命名空间,那么就要把c++ 中所有函数前段表上作用域:std::,如下图
#include <iostream>
using namespace std;
int main() {
cout << "!!!";
return 0;
}
#include <iostream>
int main() {
std::cout << "!!!";
return 0;
}
因此,在C++的头文件里的成员,如果没有使用标准命名空间(using namespace std; ),那么就要在成员前加上作用域(std::)。
好了,拓展了一下。这串代码直接输出"Hello everyone, I am a student. Nice to meet you! "
然后就要讲有哪些Format了
"%d" //整型
"%f" //浮点型
"%lf" //长浮点型
"%llf" //双长浮点型
"%.nlf" //输出n位小数
"%lld" //输出双长整型的数
"%nd" //输出数字,并设置场宽为n,左对齐
"%%" //输出 %
"%-nd" //输出数字,并设置场宽为n,右对齐
几串小实例
printf("%d-%d-%d", 16, 13, 15);
output: 16-13-15
printf("%.3lf", 3.1415926);
output: 3.142
printf("%5d", 15);
output: 15
printf("%-5d%-5d%-5d", 135, 12, 17);
output: 135 12 17
这里的换行难道又是用endl表示?上期我们讲到还能用 '\n' 表示换行,这里也是。例如"Hello\n John! \n"输出的是:
Hello
John!
好了,scanf来了,这次先讲Format再举例。
"%d" //整型
"%f" //浮点型
"%lf" //长浮点型
"%llf" //双长浮点型
"%lld" //双长整型
scanf("%d", &n);
input: A_Integer_Number
n = input[1]
scanf("%lf", &n);
input: A_Float_Pointer_Number
n = input[1]
scanf("%d-%d", &a, &b);
input: A_Digit-A_Digit
a = input[1]
b = input[2]
可以说,它相当于用后面的Fill去填前面的各个Format。
本次作业:
改进系统,再做一个加法计算器。输入格式:a+b。输出格式:a+b=c
输入样例 :
9+11
输出样例 :
20