Wartość bezwzględna pozwala obliczyć odległość od punktu zerowego. Czyli w uproszczeniu załóżmy że mamy oś liczbową i na niej naniesione liczy -5, 0, 5 Zauważmy że liczba 5 jest tak samo odległa jak liczba -5 o równe 5 działek od punktu 0. Realizacja tej funkcji jest bardzo prosta.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int wartosc_bezwzgledna(int n){ | |
if(n<0)n*=-1; | |
return n; | |
} | |
int main() { | |
int n; | |
cin>>n; | |
cout<<wartosc_bezwzgledna(n); | |
return 0; | |
} |
Oczywiście nie musimy pisać własnej funkcji wartości bezwzględnej. Została już ona za nas napisana i znajduje się w bibliotece algorithm. Funkcja zaś nazywa się abs(liczba). Program skraca się do niebotycznych rozmiarów.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
int main() { | |
int n; | |
cin>>n; | |
cout<<abs(n); | |
return 0; | |
} |
Brak komentarzy:
Prześlij komentarz