C++ :: Aufgabe #237 :: Lösung #2

3 Lösungen Lösungen öffentlich
#237

Array von Zahlen in die nächstgelegene durch 5 teilbare Zahl umwandeln

Anfänger - C++ von Gustl - 08.05.2019 um 20:08 Uhr
Schreibe ein Programm welches aus einem Array von Dezimalzahlen diese Zahlen in die nächstgelegene durch 5 teilbare Zahl umwandeln.

Etwa so:

Konsolenausgabe:

 7.1 => 5
8.4 => 10
-2.4 => 0
-2.6 => -5
-8.3 => -10
#2
vote_ok
von EuPr (130 Punkte) - 27.06.2019 um 13:01 Uhr
Quellcode ausblenden C-Code
#include<iostream>
#include<vector>
#include<sstream>
#include<tgmath.h>

using namespace std;


bool IsFloat( string myString ) {
    std::istringstream iss(myString);
    float f;
    iss >> noskipws >> f; // noskipws considers leading whitespace invalid
    // Check the entire string was consumed and if either failbit or badbit is set
    return iss.eof() && !iss.fail();
}

int main() {
  cout << "5-Teiler-Programm - bitte geben Sie Zahlen ein, bis Ihre Zahlenfolge durch ein # beendet wird.\n"
          "Anschliessend erfolgt die Berechnung.\n";
  vector<float> fltVect{};
  while (1) {
    string Input;
    cout << ">>";
    cin >> Input;
    if (IsFloat(Input))
    {
        fltVect.push_back(stof(Input));
    }
    else if (Input == "#")
    {
        break;
    }
    else
    {
        cout << "Ungültige Eingabe. Zum Beenden der Eingabe genuegt ein #.";
    }
  }
  cout << "Ausgabe Inhalt:\n";
  for (std::vector<float>::iterator it = fltVect.begin() ; it != fltVect.end(); ++it)
  {
     float fMyFloor = floor(*it / 5);
     float fRest = *it - (fMyFloor * 5);
     if (fRest <2.5) {*it = *it - fRest;}
     else {*it = *it + (5 - fRest);}
     cout << *it << "\n";
  }
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben