C++ :: Aufgabe #237

3 Lösungen Lösungen öffentlich

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

Lösungen:

vote_ok
von EuPr (130 Punkte) - 27.06.2019 um 11:32 Uhr
Quellcode ausblenden C-Code
float fMyFloor = floor(*it / 5);           //ganzzahlige Division, über floor IMMER abgerundet
float fRest = *it - (fMyFloor * 5);        //Modulo-Rest eines Float somit errechnet
if (fRest <2.5) {*it = *it - fRest;}       //goldene Mitte 2.5 -> vorher abrunden
  else {*it=*it + (5 - fRest);}            //.. ansonsten aufrunden
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";
  }
}
vote_ok
von DaDude1105 (110 Punkte) - 19.08.2019 um 16:38 Uhr
Quellcode ausblenden C-Code
# include <iostream>
#include <math.h> 
using namespace std;

int main()
{
	int array [5] = { 0 };	
	for (int counter = 0; counter < 5; counter++)
	{
		double input = 0;
		cout << "Input " << counter+1<<": ";
		cin >> input;
		array[counter] = round(input);
		if (array[counter] % 5 != 0)
		{
			for (int i = -2; i <= 2; i++)
			{
				if ((array[counter]+i) % 5 == 0)
				{
					array[counter] = array[counter] + i;
				}
			}
		}
	}
	for (int i = 0; i < 5; i++)
	{
		cout << " " << array[i];
	}
}
1800892

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.