简体   繁体   中英

Finding closest number

I have the following .txt file:

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.

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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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