I'm taking a C++ class, as I just started my first year of college and it has been destroying me. I have been attempting for hours to do my homework but can't come to a solution.
My assignment is to make a C++ program that when given minutes will tell you years and days.
We have been using float and cout and cin in class and some % and / structures which are foreign to me. If someone could help that would be great because I lost all hope at this point.
#include <iostream>
using namespace std;
float = minutes
float = hours
float = days
float = years
float = seconds
int main()
{
using namespace std;
int days, years, minutes, hours, seconds;
cout << "Please Enter Minutes" << endl;
cin >> minutes;
days = input_minutes / 60 / 60 / 24;
hours = (input_minutes / 60 / 60) % 24;
minutes = (input_minutes / 60) % 60;
seconds = input_minutes % 60;
cout << days << " seconds = " << years << " years ";
cin.get();
cin.get();
return 0;
}
I took the liberty to look at the code that you have into the comment box;
first thing :
Declare a variable to store the input value or save the result of a computation
int days; //<--- declaration of a int variable called days
so this in line I don't know what you were trying to do but float = minutes float = hours float = days float = years float = seconds
Please don't do it
second thing:
Don't repeated `using namespace std` twice. Therefore remove it from the `int main` function.
Third :
your computation is kinda OFF, try to solve mathematically then code it.
your code should look like that: (This is not the answer)
#include <iostream>
using namespace std;
int main()
{
int days, years, input_minutes, hours, seconds,minutes;
cout << "Please Enter Minutes" << endl;
cin >> input_minutes;
days = input_minutes / 60 / 60 / 24;
hours = (input_minutes / 60 / 60) % 24;
minutes = (input_minutes / 60) % 60;
seconds = input_minutes % 60;
cout << days << " seconds = " << years << " years ";
system("Pause");
return 0;
}
I can give you a little help on what each of those means. Here are the non-super technical definitions.
A float is an integer that can have decimal places.
cout Will output the value next to <<
cin will store a value from an input (cin >> x) will store the user input in x.
% is the modulus character. It will return the remainder after the division of two numbers. 3%2 will return 1.
/ is just simple, plain old, division.
Joe, I think we shouldn't do that job for you, and this is not exactly a "technical" question. Considering this, I will try to give you some ideas.to get some extra scores:
1 - take the user input, "the number of minutes" from command line args, like:
int main(int argc, char *argv[]) {
int num_mim = atoi(argv[1]);
2 - to take the number of years do int num_years = num_mins / (60 * 24 * 365);
(not taking into account leap years)
3 - to take the number of days do int num_days = num_mins % (60 * 24 * 365) / 60 / 24;
of course simplify the operations by performing the multiplications and divisions that can be made by hand if you want.
% is the modulos operator, it gives you the remainder of the dvision, here we use it to get the remainder of minutes from the years cound and express it in days.
Now it is up to you, look for additional sources of info and assemble your homework.
Related
Title is just an example.
I am making an app in C++ and need to show the time required to achieve a given point. If I go to alpha centauri at light speed, I would reach it after 4 years 133 days, but the output is 4.367 years.
How can I convert 4.367 years to 4 years 133 days?
#include <iostream>
using namespace std;
int main()
{
double percent = 0;
double speed_light = 1 ; // Light/Years
double alpha_centauri = 4.367;
double alpha_centauri_days = 1595.0467;
cout << "Please inter the percentage of light speed the spaceship is flying with:\n";
cin >> percent;
double per_speed = percent * speed_light /100;
double year_time = alpha_centauri / per_speed ;
int days_time = alpha_centauri_days / per_speed ;
cout <<"The time required to reach alpha centauri at "<< percent
<< " percent of light speed is: \n"<< year_time << " years!\t" << days_time<< " days!\n";
return 0;
}
Making the simplifying assumption that one year equals 365 days. Then divide by 365 to get the years, and modulo 365 to get the days left over.
int days_time = alpha_centauri_days / per_speed ;
cout <<"The time required to reach alpha centauri at "<< percent
<< " percent of light speed is: \n"<< days_time/365 << " years!\t" << days_time%365 << " days!\n";
You don't need the year_time variable.
x-floor(x) gives you fractional part.
(x-floor(x))*365.25 gives days left after years are removed from x.
I am looking for help in C++ converting an integer input into 24 hours format.
Suppose you build a scheduled time for airplanes from A (start) to B (end); The user is able to entry 4 different variables, such as the journey time of the airplane from A to B; the first airplane time; the last airplane time; and the frequency of traveling in one day.
The input would be like the following:
int journey_time;
int start_time;
int end_time;
int frequency;
cout << "Please enter your journey time:\n";
cin >> journey_time;
cout << "Please enter your start time:\n";
cin >> start_time;
cout << "Please enter your end time: \n";
cin >> end_time;
cout << "Please enter the frequency: \n";
cin >> frequency;
IMPORTANT to mention is that the user should type in the times as integer and the hours should be transformed in a 24 hour clock times
And this is where I am stucked; I was able to transform the integer into minutes but not into hours
so far I have this code
for (int total_min_start= start_time; total_min_start <= end_time; total_min_start +=frequency)
{
hs = total_min_start/100; // to get the hours
ms = total_min_start %100; // to get the minutes
x = (hs *60) + ms; // converted into minutes
h = ((x-ms)/60) * 100; <= this is where I am confused, I want here the reconversion of hours into to 24 hours format
t = h + ms; // this is the total time after reconversion
cout << t << "\t" << t + journey_time<< endl;
}}}
if I type in for journey time=15; start_time=0930; end_time= 1000 and frequency = 15 min, i get the following output (left) but I want this output (right)
WRONG OUTPUT RIGHT OUTPUT
930 945 930 945
945 960 945 1000
960 1000 1000 1015
I would be very very thankful for any kind of help or hint...
Thanks in advance
Okay lets unroll the loop and do each step separately.
First iteration:
// Loop initialization
total_min_start = 930;
hs = 930 / 100; // 9
ms = 930 % 100; // 30
x = (9 * 60) + 30; // 540 + 30 = 570
h = ((570 - 30) / 60) * 100; // (540 / 60) * 100 = 9 * 100 = 900
t = 900 + 30; // 930
// t + journey_time = 930 + 15 = 945
total_min_start += 15; // 945
So far so good, so we start the second iteration:
total_min_start = 945;
hs = 945 / 100; // 9
ms = 945 % 100; // 45
x = (9 * 60) + 45; // 540 + 45 = 585
h = ((585 - 45) / 60) * 100; // (540 / 60) * 100 = 9 * 100 = 900
t = 900 + 45; // 945
// t + journey_time = 945 + 15 = 960
total_min_start += 15; // 960
Ah here it seems we have a problem. The value in t is not the time in minutes, it's actually two separate values: Hours and minutes.
There are two ways to solve this: As soon as the user have entered the input, separate it into the two values, and keep track of the time in two separate variables.
The second way to solve it, and which I think is much easier, is to immediately after input convert the input into a single value, whose unit is the number of minutes after midnight. That is, if the user inputs 930 meaning 9:30 AM, you convert it into the value 570 (which is the number of minutes after midnight). Then work only with that value, increase and decrease as you wish, and only convert it back to your preferred format when presenting it to the user.
To help you with the conversions back and forth I suggest you have a couple of utility or helper functions: One for converting the timestamp into minutes past midnight, and one for converting the number of minutes past midnight into the timestamp. Then you could easily do something something like
cout << minutes_to_time(t) << '\t' << minutes_to_time(t + journey_time) << '\n';
Oh, and don't forget to test for wrapping around at midnight. Both ending up with t being exactly midnight, with t + journey_time being midnight, and with t being a little before midnight and t + journey_time being a little after midnight.
Create separate functions to convert minutes into 24 hour time format and vice versa.
auto get_24hr = [](int minutes){ return (minutes/60)*100 + (minutes%60);};
auto get_minutes = [](int time_24){return (time_24/100)*60+ (time_24 % 100);};
for (int total_min_start= start_time; total_min_start <= end_time; total_min_start +=frequency)
{
auto x = get_minutes(total_min_start); // converted into minutes
cout << get_24hr(x) << "\t" << get_24hr(x+journey_time) << endl;
}
In your program, you will have the user enter what percentage improvement in
rocket speeds (up to but not exceeding light speed!) each year. Your program will
then ask the user the maximum number of years that they are willing to wait on
earth before they leave. Use while loops in this step to implement simple error
checking by asking the user repeatedly until they give a valid input. Percentage
must be somewhere between 0 and 100 and the years waiting must be a positive
integer.
Next, your program will generate a table using a for loop. That table will have
four columns with one row for leaving immediately followed by one row for each
year the user is willing to wait. The first column will contain the departure year.
The second column contains the rocket speed that rockets will be able to achieve
that year. The new rocket speed each year is calculated with this equation:
velocity = velocity + (lightspeed - velocity) * (improvement/100)
I was able to correctly print out each year in the table I am trying to make, but I am having trouble figuring out how to use a loop to find the speed of the rocket for each year using a loop. I am pretty sure I am supposed to use a nested for loop, but with the code I have right now, it is stuck in an infinite loop. Any guidance in the right direction would be appreciated!
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
int percentIncrease = 0;
int maxYears = -1;
float speedLight = 299792;
while((percentIncrease <= 0) || (percentIncrease >= 100))
{
cout << "What percentage do rocket speeds increase by each year?" << endl;
cin >> percentIncrease;
}
while(maxYears < 0)
{
cout << "What is the maximum number of years you are willing to wait on
earth before you leave?" << endl;
cin >> maxYears;
}
cout << "Start year|\tAvg Speed|\tEarth ETA|\tYour ETA" << endl;
for(int i = 2018; i <= (maxYears + 2018); ++i)
{
cout << i << endl;
for(int j = 10000; i <= (maxYears + 2018); j = j + (speedLight - j) *
(percentIncrease/100))
{
cout << "\t" << j << endl;
}
}
return 0;
}
I think a good way to think about it is that you will have to print the table row by row. So your first for loop seems to be doing that.
In each row, you have to, first, print the year (starting with the current year) up until the maximum year. Making the first for loop iterate over the years is a good choice (i.e. making i go from 2018 until maxYears + 2018). Second, you have to print the speed for each year after calculating the improvement via the provided equation. (I'm assuming that in the problem description it was given that the first speed is 10000? If not, what is the starting value?) Because you will only print a number, you don't need a second for loop. Just calculate the new speed and print it. As for the third and fourth column, I'm not sure what is asked exactly, so for now it will be blank in the code.
I modified code based on my comments, plus a few other modifications related to my understanding of the problem description, coding best practices, and stylistic choices (read below the code for more info on why).
#include <iostream>
//--1
int main()
{
//--2
const float speedLight = 299792;
const int startingYear = 2018;
//--3
float percentIncrease = 0;
while ((percentIncrease <= 0) || (percentIncrease >= 100))
{
std::cout << "What percentage do rocket speeds increase by each year?" << std::endl;
std::cin >> percentIncrease;
}
//--4
int maxYears = -1;
while (maxYears < 1)
{
std::cout << "What is the maximum number of years you are willing to wait on earth before you leave? " << std::endl;
std::cin >> maxYears;
}
std::cout << "Year|\tAvg Speed|\tEarth ETA|\tYour ETA" << std::endl;
//--5
float currentSpeed = 10000;
for (int year = startingYear; year <= (maxYears + startingYear); ++year)
{
//--6
std::cout << year << "\t" << currentSpeed << std::endl;
currentSpeed = currentSpeed + (speedLight - currentSpeed) * (percentIncrease / 100);
}
//--7
system("pause");
return 0;
}
--1: I removed unused libraries. (You may be using them for other parts
of the program, like if you want to print float numbers). I also
removed the using namespace std; because it is a bad practice. You
can google it.
--2: These numbers seem unchanging, so it is better to make them
constants.
--3: Maybe percentIncrease is not necessarily an integer.
--4: The problem description states that the number of years is a
positive integer, so it cannot be 0.
--5: The currentSpeed (previously j) should be defined outside the
loop because it will be updated inside the loop. Plus, it is a float
because of #3.
--6: The speed should be printed after the year.
--7: This is optional, in case you want the program window to not close
immediately. You can alternatively debug there by putting a
breakpoint, or any other solution.
I wrote a program to solve the exercise below. I got my hours and minutes right, but I cannot get my seconds right.
In order to save disk space Time field in the directory entry is 2
bytes long. Distribution of different bits which account for hours,
minutes and seconds is given below:
15 14 13 12 11|10 9 8 7 6 5| 4 3 2 1 0
H H H H H| M M M M M M| S S S S S
Write a C++ Program that take input two-byte time entry and
appropriately separates hours, minutes and seconds using suitable
bitwise operators.
#include<iostream>
using namespace std;
int main()
{
unsigned int hours, mins, secs;
unsigned int time;
cout << "enter time ";
cin >> time;
hours = (time >> 11);
mins = ((time << 5) >> 10);
secs = ((time << 11) >> 11);
cout << hours << " " << mins << " " << secs << endl;
return 0;
}
To get the minutes, I shift the input to the left by 5 positions, hoping to eliminate all the H bits, and then shift to the right by 10 positions to eliminate all the S bits and have the M bits at the rightmost position.
Similarly for the seconds.
However, if I enter 445 I expect the result to be 13 minutes and 29 seconds, but the program outputs 0 13 445.
Why do the hours and minutes appear to come out correctly, but not the seconds?
secs = time & 0x1F; // This should give the 5 bits you're expecting for seconds.
You are assuming that the size of unsigned int is 16 bit but it is normally implemented as 32bit integer on nowadays machines.
If you would use uint16_t for the variable time instead it should work.
To use uint16_t include the header stdint.h.
#include <iostream>
#include <stdint.h>
using namespace std;
int main()
{
uint16_t hours, mins, secs;
uint16_t time = 445;
hours = (time >> 11);
mins = ((time << 5) >> 10);
secs = (time << 11);
secs >>= 11;
cout << hours << " " << mins << " " << secs << endl;
return 0;
}
(Tested on QT 5.5)
You should zero the bits that don't correspond to the part of time you are looking at. I will use binary literals (which are available in C++14), but comment the equivalent hex literals.
struct time {
time(unsigned = 0); // also default constructs
unsigned hours;
unsigned mins;
unsigned secs;
}
time::time(unsigned packed) :
hours((packed & 0b1111100000000000) >> 11), // 0xF800
mins ((packed & 0b0000011111100000) >> 5 ), // 0x07E0
secs ((packed & 0b0000000000011111) ) // 0x001F
{ }
#include<iostream>
std::ostream& operator<< (std::ostream& os, time t) {
return os << t.hours << " " << t.mins << " " << t.secs;
}
int main()
{
time t(445);
std::cout << t << std::endl;
return 0;
}
The task given is impossible, because 6 bits are required for both the minutes and the seconds. You have alotted 5 bits for the seconds.
2^5=32
2^6=64
Using this scheme, 17 bits are required to represent the time.
I made this program in C++, simple calculation of an interest rate of a bank a while back as part of a homework assignment. The answer is incorrect by a small margin but I still cannot understand why, and the mistake gets higher as I try higher input numbers...
The instructions on how to get this problem are commented as first lines of the program.
I tried switching the involved variables from float to double then to long double and its still the same answer...
Can anyone please figure out why?
// Homework 2 Task 1.cpp : Show bank balance after loan with user-input factors
//Try the code with 100 deposited sum, 5% interest and 3 months total time
//The answer will show 302.087 whereas the true answer should be 302.507
#include "stdafx.h"
#include <iostream>
using namespace std;
long double compoundVal(unsigned int, unsigned short int, unsigned short int);
void main()
{
unsigned int DepSum;
unsigned short int IntRate, NrMonths;
cout << "Please enther the amount you expect to deposit each month: ";
cin >> DepSum;
cout << "\nThe amount of money that you will have in your account after 6 months with Inte-rest Rate of 5% will be: "<<compoundVal(DepSum, 5, 6); //Answering the first part of this task, where the user has to specify the Deposit Sum, and will receive the amount after 6 months with interest of 5%
cout << "\n\nYou can also see the account balance with interest rate and number of months of your choice.\nPlease enter the Interest Rate of your choice: ";
cin >> IntRate;
cout << "\nNow enter the number of months you intend to have the account: ";
cin >> NrMonths;
cout << "\nThis will be your account balance: " << compoundVal(DepSum, IntRate, NrMonths) << endl;
}
long double compoundVal(unsigned int d, unsigned short int i, unsigned short int n){
long double c = (1.0 + (i / 1200.0)); //Finding the monthly percentage, and because the user inputs the yearly interest in %, we need to remove the %(*0.01) and /12 for 12 months/year.
return((1.0 + (n - 1)*c)*d*c); //The math formula that will give us the results of the calculation.
}
The formula you are using appears to be wrong - but I'm not sure where you got it or what it actually represents. The expected answer is for simple periodic compounding interest. In other words, each month you calculate newbalance = balance * (1 + annualrate/12) + deposit). Iterating that 3 times for your required three months gives the expected answer of $302.5069, instead of the lower value $302.0868 you get from your formula.
The formula you are using is wrong.
The value of the first month's deposit at the end of 3 months: d.c^3
The value of the second month's deposit at the end of 3 months: d.c^2
The value of the third month's deposit at the end of 3 months: d.c
If you generalize it to N months, the total value of your deposit at the end of N months will be:
d(c + c^2 + c^3 + ... + c^N)
The value of that sum is: d.c.(c^N - 1)/(c-1)
If you plugin this formula you'll get the correct answer: 302.507.
The formula
sum = d(c + c^2 + c^3 + ... + c^N)
Multiplying both side by c,
sum.c = d(c^2 + c^3 + c^4 + ... + c^(N+1))
Subtracting the two equations,
sum(c-1) = d(c^(N+1) - c) = d.c(c^N - 1)
sum = d.c(c^N - 1)/(c-1)