简体   繁体   English

寻找最近的号码

[英]Finding closest number

I have the following .txt file: 我有以下.txt文件:

23 43 -10
65 1 -1
-3 3 3
400 401 -389
21 6 -6
0 0 0

I need to write a program that will read data from the file until it reads the line with three 0's. 我需要编写一个程序,该程序将从文件中读取数据,直到它读取带有三个0的行。

I then need to write a function that accepts the three integer numbers and returns the number closest to 0. If two or three values are the same distance from 0 return the first number that is closest to 0. 然后,我需要编写一个函数,该函数接受三个整数并返回最接近0的数字。如果两个或三个值与0的距离相同,则返回最接近0的第一个数字。

This is what I have so far: 这是我到目前为止的内容:

#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int findClosest(int, int, int);

int main()
{
    ifstream fin;
    infile.open("LAB5DATA.TXT");

    int a, b, c;

    while (infile >> a >> b >> c && a + b + c != 0)
    {     
    int closest = findClosest(a, b, c);
    cout << closest << endl;
    }
    infile.close();
    return 0;
}

int findClosest(int a, int b, int c)
{
    int differenceA = abs(a - 0);
    int differenceB = abs(b - 0);
    int differenceC = abs(c - 0);

    int closest = differenceA;
    if (differenceB < closest)
        closest = differenceB;
    if (differenceC < closest)
        closest = differenceC;

    return closest;
}

Any help would be greatly appreciated! 任何帮助将不胜感激!

I would fix your findClosest function by making a couple of changes. 我将通过进行一些更改来修复您的findClosest函数。 First off, define a function that takes the absolute of an integer so that you can compare the differences more cleanly. 首先,定义一个函数,该函数采用整数的绝对值,以便您可以更清晰地比较差异。

Then from there, simply return the minimum of the 3 differences. 然后从那里简单地返回3个差异中的最小值。

Edited: 编辑:

int findClosest(int a, int b, int c)
{
    int closest = a;
    if (abs(b) < abs(a)) closest = b;
    if (abs(c) < abs(b)) closest = c;
    return closest;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM