Problema
La classe di scienze ha bisogno di una tabella di conversione da stampare. Per ogni temperatura Fahrenheit da start a stop, con passo step, calcola Celsius = (F − 32) × 5 / 9 e arrotondala a una cifra decimale (al decimo più vicino; con questi input non capita mai una metà esatta).
Ogni riga ha la forma 50 F = 10.0 C: il valore Fahrenheit, F = , il valore Celsius con esattamente una cifra dopo il punto, e C. I valori negativi hanno un - davanti, ad esempio 0 F = -17.8 C e 31 F = -0.6 C.
Implementa temperature_table(start, stop, step).
Input
start: il primo valore Fahrenheit.
stop: l'ultimo valore ammesso; viene incluso se i passi ci arrivano esattamente.
step: quanto aggiungere ogni volta.
Output
Restituisci le righe in ordine: start, start + step, start + 2·step, … finché il valore non supera stop. Se start è maggiore di stop, restituisci una lista vuota.
Vincoli
−500 ≤ start, stop ≤ 1 000
1 ≤ step ≤ 100
Esempi
Input:
start = 32
stop = 72
step = 20
Output atteso:
expected = ["32 F = 0.0 C", "52 F = 11.1 C", "72 F = 22.2 C"]
Input:
long long start = 32;
long long stop = 72;
long long step = 20;
Output atteso:
std::vector<std::string> expected = {"32 F = 0.0 C", "52 F = 11.1 C", "72 F = 22.2 C"};
Input:
long start = 32;
long stop = 72;
long step = 20;
Output atteso:
string[] expected = new string[] {"32 F = 0.0 C", "52 F = 11.1 C", "72 F = 22.2 C"};
Spiegazione
32 F sono esattamente 0.0 C, 52 F sono 11.11…, che si arrotonda a 11.1, e 72 F sono 22.22…, che si arrotonda a 22.2.
Input:
start = 0
stop = 35
step = 31
Output atteso:
expected = ["0 F = -17.8 C", "31 F = -0.6 C"]
Input:
long long start = 0;
long long stop = 35;
long long step = 31;
Output atteso:
std::vector<std::string> expected = {"0 F = -17.8 C", "31 F = -0.6 C"};
Input:
long start = 0;
long stop = 35;
long step = 31;
Output atteso:
string[] expected = new string[] {"0 F = -17.8 C", "31 F = -0.6 C"};
Spiegazione
0 F sono −17.77…, che si arrotonda a -17.8; il valore successivo, 31 F, è −0.55…, che si arrotonda a -0.6; 62 supera 35, quindi la tabella si ferma.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Lavora in decimi di grado: (F − 32) × 50 / 9 dà i gradi Celsius × 10.
Suggerimento 2
Arrotonda il valore assoluto, poi rimetti il segno.
Suggerimento 3
Scrivi i decimi come parte intera, un punto e l'ultima cifra; attenzione a valori come -0.6.
Complessità attesa
tempo O(n), spazio aggiuntivo O(n)
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.