[英]Finding closest number
我有以下.txt文件:
23 43 -10
65 1 -1
-3 3 3
400 401 -389
21 6 -6
0 0 0
我需要编写一个程序,该程序将从文件中读取数据,直到它读取带有三个0的行。
然后,我需要编写一个函数,该函数接受三个整数并返回最接近0的数字。如果两个或三个值与0的距离相同,则返回最接近0的第一个数字。
这是我到目前为止的内容:
#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;
}
任何帮助将不胜感激!
我将通过进行一些更改来修复您的findClosest
函数。 首先,定义一个函数,该函数采用整数的绝对值,以便您可以更清晰地比较差异。
然后从那里简单地返回3个差异中的最小值。
编辑:
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.