C# :: Aufgabe #262 :: Lösung #2

8 Lösungen Lösungen öffentlich
#262

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
2 Kommentare
1x
vote_ok
von DBqFetti (2480 Punkte) - 24.05.2019 um 10:48 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		double[] _in = {7.1, 8.4, -2.4, -2.6, -8.3};
		double[] _out = _in.Select(x => round(x, 5)).ToArray();
		
		for(int i = 0; i < _in.Length; i++){
			Console.WriteLine("{0} => {1}", _in[i], _out[i]);
		}
	}
	
	private static int round(int val, int factor){
		return (int)(Math.Round((double)val / (double)factor, 0) * factor);
	}
	
	private static float round(float val, float factor){
		return (float)(Math.Round((double)val / (double)factor, 0) * factor);
	}
	
	private static double round(double val, double factor){
		return Math.Round(val / factor, 0) * factor;
	}
	
	private static decimal round(decimal val, decimal factor){
		return Math.Round(val / factor, 0) * factor;
	}
}

Kommentare:

hollst

Punkte: 13980

761 Aufgaben
132 Lösungen
117 Kommentare

#1
13.06.2019 um 18:23 Uhr
Hallo,

verstehe die vielen Fallunterscheidungen bei "static.round" nicht.

Wozu sind die nötig?

Gruß

post_arrow
585 0

DBqFetti

Punkte: 2480


53 Lösungen
20 Kommentare

#2
14.06.2019 um 07:13 Uhr
In der Aufgabenbeschreibung wird nur von Zahl gesprochen. Eine Zahl kann aber durch viele unterschiedlichen Typen repräsentiert werden, in C♯. Der exemplarische Aufruf in der Main() benötigt diese alle freilich nicht.
post_arrow
586 0
Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben