scanf?printf!

上期参考答案,你做对了吗:

#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

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值