微软编程一小时题目一

原题如下:

题目1 : Arithmetic Expression

时间限制: 2000ms
单点时限: 200ms
内存限制: 256MB

描述

Given N arithmetic expressions, can you tell whose result is closest to 9?

输入

Line 1: N (1 <= N <= 50000).
Line 2..N+1: Each line contains an expression in the format of "a op b" where a, b are integers (-10000 <= a, b <= 10000) and op is one of addition (+), subtraction (-), multiplication (*) and division (/). There is no "divided by zero" expression.

输出

The index of expression whose result is closest to 9. If there are more than one such expressions, output the smallest index.

样例输入
4
901 / 100
3 * 3
2 + 6
8 - -1
样例输出
2
这道题目属于基础编程题,没有涉及复杂算法,主要考察了基本的输入输出控制和运算法则,但由于对VS使用的不够熟练,本体的输入输出一直没有搞定,从而导致两道题目都没有经过在线测试。还是要加强训练才行啊!!!

自己编写的源码:

#define _CRT_SECURE_NO_DEPRECATE
#include"stdafx.h"
#include <stdio.h>
#include<math.h>
int main(){
	int N;
	int a,b,index = 0;
	char c;
	double result,min = 32767;
	scanf("%d",&N);
	for(int i = 0; i < N;i++){
		scanf("%d %c %d",&a,&c,&b);
		if(c == '+')
			result = a + b;
		else if(c == '-')
			result = a - b;
		else if(c == '*')
			result = a * b;
		else
			result = (double)a / b;
		double temp = fabs(result - 9);
		if(temp < min){
		    min = temp;
			index = i + 1;
		}
	}
	printf("%d\n",index);
	return 0;
}
编程过程中要注意的是由于VS的严格控制,所以在做算法题是最好自己重新编写main()函数,这里涉及宏定义的添加和预定义头文件的设置,具体设置方法见:

http://www.csdn123.com/html/itweb/20130730/29594_29603_29609.htm

另外,在本题中,由于结果保留为double型,所以在做除法前需要先将至少一个操作数转换成double类型

本题没有经过在线测试,有问题还请指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值