[英]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.