题目
The Goal
In this exercise, you have to analyze records of temperature to find the closest to zero.
Rules
Write a program that prints the temperature closest to 0 among input data. If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5).
Game Input
Your program must read the data from the standard input and write the result on the standard output.
Input
Line 1: N, the number of temperatures to analyze
Line 2: A string with the N temperatures expressed as integers ranging from -273 to 5526
Output
Display 0 (zero) if no temperatures are provided. Otherwise, display the temperature closest to 0.
Constraints
0 ≤ N < 10000
Example
Input
5 1 -2 -8 4 5
Output
1
解题代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int closet = 5526;
int sy = -1;
int n; // the number of temperatures to analyse
cin >> n; cin.ignore();
for (int i = 0; i < n; i++) {
int t; // a temperature expressed as an integer ranging from -273 to 5526
cin >> t; cin.ignore();
if(t > 0)
{
sy = 0;
if(t < closet)
{
closet = t;
}
}
else
{
sy = 1;
if(-t < closet)
{
closet = -t;
}
}
}
// Write an answer using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
if(sy == -1)
{
cout << "0" << endl;
}
else
{
if(sy == 1)
{
cout << "-";
}
cout << closet << endl;
}
}
解析
本题要判断距离0最近的数字,由于有没有输入的情况,因此要先判断是否有输入,没有输入就报0。随后判断目标正负,并统一按照正数距离0的远近来存储,通过判断输入变量来记录正负,最后输出的时候要还原正负性。