您的位置:首页 > 其它

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;
}


运行结果:

Accepted117015MS1956K553B
题解:

要注意做除法的结果,如果两个数的数据类型都是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则是保留三位,以此类推。——》百度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: