0

Bon Voyage!

Greetings everyone. I'm new to coding. This question gave me issues so I thought I would share my solution. Once I solved it successfully, I googled the question to see what others came up with. Their solutions were different. Everyone solved it in a way that assumes you know the boat traveled 200 km. I know it is simple math, but I wanted a way for this to work with any set of numbers without doing mental math lol. If any expert sees this, feel free to chime in! You are on a 5 hour sea voyage. The ship sails at a speed of 40 km per hour. Write a program that will output how many kilometers the ship has traveled by each hour. #include <iostream> using namespace std; int main() { int distance = 0; // inital distance, will be updated as we go int time = 5; // how many hours int speed = 40; // km per hour int sum ; // too distance based on hours at set speed sum = speed * time; for (distance = 40; distance <= sum; distance += 40) { /* if traveling a 40 km per hour, when the distance is less than or equal to the total distance; increment the km per hour by 40 */ cout << distance << endl; // print the distance traveled each km on a separate line } return 0; } https://code.sololearn.com/ca21a2183A10/#cpp

28th May 2021, 8:53 PM
TeAiris Majors
TeAiris Majors - avatar
5 odpowiedzi
+ 1
https://code.sololearn.com/cBAHGFQOpiV3/?ref=app
29th May 2021, 5:31 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
The formula is just speed into time
29th May 2021, 5:34 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
My code is kinda similar to yours. #include <iostream> using namespace std; int main() { int speed = 40; for(int hours = 1; hours <= 5; hours++) { //how many kilometers traveled. int kilometers; kilometers = speed * hours; cout << kilometers << endl; } }
10th Mar 2022, 7:50 PM
Brandon
0
Thanks for the response. However your code with only tell the total distance traveled. The challenge was to get the program to print the total distance for each hour traveled. My issue was with other solutions I found that took the shortcut of telling the program to basically print in increments of 40 until it was equal to 200. I let the program figure that out using the numbers i was given lol
30th May 2021, 4:30 AM
TeAiris Majors
TeAiris Majors - avatar
0
Bon voyage c++ recursive solution #include <iostream> using namespace std; void sum(int hours){ if(hours==0){ return; } sum(hours-1); int add = 0; add+=40*hours; cout<<add<<endl; } int main() { int distance = 0; //your code goes here sum(5); return 0; }
17th Aug 2022, 3:25 AM
SHUBHAM KUMAR
SHUBHAM KUMAR - avatar