fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Function to add two distances and update the first one
  5. void addDistance(int &km1, int &m1, int km2, int m2) {
  6. // Validate meters input
  7. if (m1 < 0 || m1 >= 1000 || m2 < 0 || m2 >= 1000) {
  8. cout << "Error: Meters must be less than 1000!" << endl;
  9. return;
  10. }
  11.  
  12. // Add kilometers and meters separately
  13. km1 += km2; // Add kilometers
  14. m1 += m2; // Add meters
  15.  
  16. // If meters exceed 1000, convert them to kilometers
  17. if (m1 >= 1000) {
  18. km1 += m1 / 1000; // Convert excess meters to kilometers
  19. m1 = m1 % 1000; // Keep the remainder as meters
  20. }
  21.  
  22. // Display the final result
  23. cout << "Total Distance: " << km1 << " Kilometers and " << m1 << " Meters" << endl;
  24. }
  25.  
  26. int main() {
  27. int km1, m1, km2, m2;
  28.  
  29. // Input first distance
  30. cout << "Enter the first distance (Kilometers and Meters): ";
  31. cin >> km1 >> m1;
  32.  
  33. // Input second distance
  34. cout << "Enter the second distance (Kilometers and Meters): ";
  35. cin >> km2 >> m2;
  36.  
  37. // Call addDistance to compute the total distance
  38. addDistance(km1, m1, km2, m2);
  39.  
  40. return 0;
  41. }
  42.  
  43.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Enter the first distance (Kilometers and Meters): Enter the second distance (Kilometers and Meters): Error: Meters must be less than 1000!