F.X — podsumowanie rozdziału F i quiz

A constexpr funkcja to funkcja, którą można wywołać w wyrażeniu stałym. Aby uczynić funkcję funkcją constexpr, po prostu używamy słowa kluczowego constexpr przed typem zwracanym. Funkcje Constexpr mają gwarancję, że zostaną ocenione w czasie kompilacji tylko wtedy, gdy zostaną użyte w kontekście wymagającym stałego wyrażenia. W przeciwnym razie mogą być oceniane w czasie kompilacji (jeśli kwalifikują się) lub w czasie wykonywania. Funkcje Constexpr są domyślnie wbudowane i kompilator musi zobaczyć pełną definicję funkcji constexpr, aby wywołać ją w czasie kompilacji.

A Funkcja constexval to funkcja, która musi zostać obliczona w czasie kompilacji. W przeciwnym razie funkcje Consteval działają na tych samych zasadach, co funkcje constexpr.

Czas quizu

Pytanie nr 1

Dodaj const i/lub constexpr do następującego programu:

#include <iostream>

// gets tower height from user and returns it
double getTowerHeight()
{
	std::cout << "Enter the height of the tower in meters: ";
	double towerHeight{};
	std::cin >> towerHeight;
	return towerHeight;
}

// Returns ball height from ground after "seconds" seconds
double calculateBallHeight(double towerHeight, int seconds)
{
	double gravity{ 9.8 };

	// Using formula: [ s = u * t + (a * t^2) / 2 ], here u(initial velocity) = 0
	double distanceFallen{ (gravity * (seconds * seconds)) / 2.0 };
	double currentHeight{ towerHeight - distanceFallen };

	return currentHeight;
}

// Prints ball height above ground
void printBallHeight(double ballHeight, int seconds)
{
	if (ballHeight > 0.0)
		std::cout << "At " << seconds << " seconds, the ball is at height: " << ballHeight << " meters\n";
	else
		std::cout << "At " << seconds << " seconds, the ball is on the ground.\n";
}

// Calculates the current ball height and then prints it
// This is a helper function to make it easier to do this
void printCalculatedBallHeight(double towerHeight, int seconds)
{
	double ballHeight{ calculateBallHeight(towerHeight, seconds) };
	printBallHeight(ballHeight, seconds);
}

int main()
{
	double towerHeight{ getTowerHeight() };

	printCalculatedBallHeight(towerHeight, 0);
	printCalculatedBallHeight(towerHeight, 1);
	printCalculatedBallHeight(towerHeight, 2);
	printCalculatedBallHeight(towerHeight, 3);
	printCalculatedBallHeight(towerHeight, 4);
	printCalculatedBallHeight(towerHeight, 5);

	return 0;
}

Pokaż rozwiązanie

guest
Twój adres e-mail nie zostanie wyświetlony
Znalazłeś błąd? Zostaw komentarz powyżej!
Komentarze związane z poprawkami zostaną usunięte po przetworzeniu, aby pomóc zmniejszyć bałagan. Dziękujemy za pomoc w ulepszaniu witryny dla wszystkich!
Awatary z https://gravatar.com/ są połączone z podanym adresem e-mail.
Powiadamiaj mnie o odpowiedziach:  
35 Komentarze
Najnowsze
Najstarsze Najczęściej głosowane
Wbudowane opinie
Wyświetl wszystkie komentarze