hdu 1170(Ballon Comes!)
2015-07-29 15:49
267 查看
Balloon Comes!(原网址:http://acm.hdu.edu.cn/showproblem.php?pid=1170)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 23043 Accepted Submission(s): 8712
[align=left]Problem Description[/align]
The contest starts now! How excited it is to see balloons floating around. You, one of the best programmers in HDU, can get a very beautiful balloon if only you have solved the very very very... easy problem.
Give you an operator (+,-,*, / --denoting addition, subtraction, multiplication, division respectively) and two positive integers, your task is to output the result.
Is it very easy?
Come on, guy! PLMM will send you a beautiful Balloon right now!
Good Luck!
[align=left]Input[/align]
Input contains multiple test cases. The first line of the input is a single integer T (0<T<1000) which is the number of test cases. T test cases follow. Each test case contains a char C (+,-,*, /) and two integers A and B(0<A,B<10000).Of
course, we all know that A and B are operands and C is an operator.
[align=left]Output[/align]
For each case, print the operation result. The result should be rounded to 2 decimal places If and only if it is not an integer.
[align=left]Sample Input[/align]
4 + 1 2 - 1 2 * 1 2 / 1 2
[align=left]Sample Output[/align]
3 -1 2 0.50
题意:
给你一个数字n,随后有n组数据。每组数据为一个符号和两个数字。如果是+号,则计算后两个数字的和;如果是-号,则计算后两个数字的差;如果是*号,则计算后两个数字的积;如果是/号,则计算后两个数字的商。注意:如果是/号,则计算后两个数字的商,如果这个商为小数,则保留小数点后两位,否则正常输出。
参考代码:
#include<iostream> using namespace std; int main() { int n,i,a,b; char c; cin>>n; for(i=0;i<n;i++) { cin>>c>>a>>b; if(c=='+')cout<<a+b; else if(c=='-')cout<<a-b; else if(c=='*')cout<<a*b; else if(c=='/') { if(a/b==(double)a/b) cout<<a/b; else printf("%.2f",(double)a/b); } cout<<endl; } return 0; }
运行结果:
Accepted | 1170 | 15MS | 1956K | 553B |
要注意做除法的结果,如果两个数的数据类型都是int,那么得到的结果也是保留到整数的结果,所以计算时需要进行强制转换(直接把数据类型定义成double也可以,但不建议那样做,因为那样判断商是否为整数就会麻烦一些)。
判断商是否为整数的方法是做两次除法,一次不强制转换,一次强制转换,如果两次的结果相等则商为整数。
第3点就是输出,不建议用cout,直接用printf("%.2f",n);即可(用法见参考知识)。
参考知识:
printf:c语言标准格式化输出。(最好定义#include<stdio.h>,有些编译器兼容不进行#include<stdio.h>,但有些不支持,需注意!):printf("",);引号中是格式化字符(例如输出Hello就放在引号里就行了)如果想输出变量就在引号中打%变量类型:int类型用%d;double、float类型用%f;等。我的程序中用了printf("%.2f");这是指将float、double类型变量保留小数点后两位后输出;%.3f则是保留三位,以此类推。——》百度。
相关文章推荐
- Sybase 当中进行增量备份的几点注意事项
- spring security3 笔记
- 11 12 15
- 挑战编程 优先队列
- 【转】增强 scite 编辑器的代码提示功能
- Rails的Custom configuration配置redis
- Install and Evaluation of Yahoo's Kafka Manager
- Android 隐藏输入法
- XP打印时提示后台服务未运行
- 如何通过Linux命令行使用和运行PHP脚本
- Facebook React Native 初探
- sort排序 文件通配符
- IDEA 分享项目到 Git
- LeetCode题解——Divide Two Integers
- js判断undefined类型,undefined,null,NaN的区别
- ftp文件及文件夹操作
- LeetCode_235 Lowest Common Ancestor of a Binary Search Tree
- 【转载】一个苹果证书怎么多次使用——导出p12文件
- golang中使用mongodb的操作类以及如何封装
- hdoj 4786 Fibonacci Tree【并查集+最小生成树(kruskal算法)】