Frage

I have a file that has a list of integers in it and trying to find which is closest to 200. I have been working on this off and on all day and have tried to do this myself a lot before coming here. I know that I have to take the different and compare it but that's all I have got so far. We have not covered array's or creating functions yet.

list of number in file 55 67 458 23 81 33 782 375 528 405 324 950 46 14 864 551 38 167 518 630

code I have so far is

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main()
{
ifstream datain;
datain.open("c:\\DataFile2.txt");
int count, sum, num, min, max;
count = sum = num = min = max = 0;

while(datain)
{
   datain >> num;
   sum = abs(num - 200);
   if(sum < min)
      sum = num;
}

The variable names don't make that much sense because I am reusing them from other parts of the program. I have tried different variations of this and i have tried other ways. the output is always the number they are set to at the begining. I still cannot figure this out and would appreciate any help I can get.

War es hilfreich?

Lösung

The problem is you're initializing min with 0, so the condition sum < min will never be true.

A simple solution is to initialize min using the first value you get from datain before entering the loop.

Though as chris said, there are more elegant solutions like using std::min_element.

Andere Tipps

If you have a vector of anything sortable and comparable with less-than (<), this might be a solution:

#include <algorithm>
#include <vector>
using namespace std;

/*
 * Find the element in haystack closest to needle.
 * NOTE: haystack must be sorted
 */
template<typename T>
T find_closest (T needle, std::vector<T> haystack) {

    /* handle special cases where needle
     * is smaller than the first or bigger
     * than the last element
     */
    if (needle <= haystack.front()) {
        return haystack.front();
    }
    if (needle >= haystack.back()) {
        return haystack.back();
    }

    auto closest = adjacent_find(haystack.begin(), haystack.end(),
        [&needle] (T i, T j) {return i =< needle && needle <= j;});

    return (needle-(*closest) < *(closest+1)-needle) ? *closest : *(closest+1);
}

int main ()
{
    int needle = 200;
    std::vector<int> haystack = {55, 67, 458, 23, 81, 33, 782, 375, 528, 405, 324,
                                 950, 46, 14, 864, 551, 38, 167, 518, 630};
    sort(haystack.begin(), haystack.end());
    int found = find_closest(needle, haystack);
}

There are a few things:

num = 0 is wrong not saving the best number is wrong

go for min = MAXINT;

int besthit;
while(datain)
{
   datain >> num;
   sum = abs(num - 200);
   if(sum < min) {
      besthit = num;
      min = sum;
   }
}

should do it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top