【Codingame】Temperatures(Easy)

本文介绍如何用C++编写程序,分析输入的温度数据,找出最接近0的值,考虑正数优先。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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的远近来存储,通过判断输入变量来记录正负,最后输出的时候要还原正负性。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值