C++ Basic Syntax Practice – Nested Branches and Ternary Operations (Part 2)

3.B2046 Cycling and Walking

C++ Basic Syntax Practice - Nested Branches and Ternary Operations (Part 2)

#include <iostream>
using namespace std;
int main() {
	float n;
	cin >> n;  // Walking
	float walk = n / 1.2;  // Cycling
	float bike = 23 + 27 + n / 3.0;
	if (walk < bike) {
		cout << "Walk";
	} else if (bike < walk) {
		cout << "Bike";
	} else {
		cout << "All";
	}
	return 0;
}

4. B2048 Calculate Postage

C++ Basic Syntax Practice - Nested Branches and Ternary Operations (Part 2)

#include <iostream>
#include <cmath>
using namespace std;
int main() {
	int x, m;
	char c;
	cin >> x >> c;
	if (x <= 1000) { // Weight within 1000
		m = 8; // Basic fee 8
	} else {
		// Calculate how many 500s exceed 1000, rounding up
		float a = (x - 1000) / 500.0;
		int b = ceil(a);
		// Fee = basic fee 8 + excess part * 4
		m = 8 + b * 4;
	}
	// If urgent, add 5 yuan
	if (c == 'y') {
		m += 5;
	}
	cout << m;
	return 0;
}

Leave a Comment