I made a code to convert time into minutes and seconds using constructor. In output I'm getting time in seconds but its not displaying time in minutes and can't figured out my mistake so anyone can help me out...
#include<iostream>
using namespace std;
class Time
{
public:
Time(int);
Time(float);
};
Time::Time(int t)
{
cout << "Time in seconds: " << t*60*60 << "\n";
}
Time::Time(float t)
{
cout << "Time in Minutes: " << int(t*60) << "\n";
}
int main()
{
int hr;
cout << "Enter the time in Hours: ";
cin >> hr;
Time t1(hr);
Time t2(float(hr));
}
You aren't typecasting correctly. You need to typecast by putting the desired type in parentheses, not by trying to use it as a function. For example, you'd need to do this:
Time t2((float) hr);
cout << "Time in Minutes: " << (int) t*60 << "\n";
While Time t2(float(hr)); is legal, it's a function prototype because this is a vexing parse. It is equivalent to Time t2(float hr);, which means that t2 is a function that takes a float called "hr" and returns a Time. This has no effect since such a function is never implemented or called.
If this seems absurd, here's a way to think about it that can help. Consider this code:
Time t2 (float (*hr));
Clearly this is a perfectly normal way to declare t2 as a function that takes a pointer to a float called "hr". Well, shouldn't it also be legal without the *? And the C++ grammar rule is that if something can be a prototype, it is.
Should works :
Time t2((float)hr);
Time::Time(int hour){
cout << "Time in seconds: " << hour*60*60 << "\n";
cout << "Time in minutes: " << hour*60 << "\n";
}
try adding
Time::Time(float t)
{
cout << "Time in Minutes: " << float(t*60) << "\n";
}
tell me if it works..
Related
So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros.
This is the code that I am using:
#include <time.h>
#include <iomanip>
using namespace std;
void linearFunction(int input)
{
for(int i = 0; i < input; i++)
{
}
}
void execution_time(int input)
{
clock_t start_time, end_time;
start_time = clock();
linearFunction(input);
end_time = clock();
double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC);
cout << "Time taken by function for input = " << input << " is : " << fixed
<< time_taken << setprecision(9);
cout << " sec " << endl;
}
int main()
{
execution_time(10000);
execution_time(100000);
execution_time(1000000);
execution_time(10000000);
execution_time(100000000);
execution_time(1000000000);
return 0;
}
And the output shows:
Time taken by function for input = 10000 is : 0.000000 sec
Time taken by function for input = 100000 is : 0.001000000 sec
Time taken by function for input = 1000000 is : 0.002000000 sec
Time taken by function for input = 10000000 is : 0.038000000 sec
Time taken by function for input = 100000000 is : 0.316000000 sec
Time taken by function for input = 1000000000 is : 3.288000000 sec
As you can see, the first time I call the function, it doesn't follow the setprecision(9) that I wrote. Why is this and how can I solve this? Thanks you in advance.
Look at the following line properly:
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9);
See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as setprecision() has already been executed, you get the desired decimal places.
So to fix this issue, move setprecision() before time_taken as such:
cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken;
..or you can also do something like this:
cout.precision(9);
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken;
Also, consider not using the following line in your code:
using namespace std;
..as it's considered as a bad practice. Instead use std:: every time like this:
std::cout.precision(9);
std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken;
For more information on this, look up to why is "using namespace std" considered as a bad practice.
I'm trying to learn how classes and their constructors work by creating a Time class that includes an hour, minute, and second. I wanted to print one time by using the default constructor and one through user input. While my program compiles, it does not ask for user input, most likely because of the way I call the class function getHour (if I were to only print the input hour). I am also unsure of how to print the time (0,0,0) through the default constructor.
Any help would be appreciated!
Main:
#include <iostream>
#include "Time.h"
int main(){
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
return 0;
}
Class implementation:
#include <iostream>
#include "Time.h"
//default constructor
Time::Time() {
hour = 0;
minute = 0;
second = 0;
}
//construct from hour, minute, second
Time::Time(int theHour, int theMinute, int theSecond) {
hour = theHour;
minute = theMinute;
second = theSecond;
}
int Time::getHour() const {
return hour;
}
int Time::getMinute() const {
return minute;
}
int Time::getSecond() const {
return second;
}
Works fine for me, this was my output:
Enter the hour, minute, and second:
2
45
32
2
Press any key to continue . . .
Make sure you are rebuilding the code and running the new executable.
In the constructor you can just do:
Time::Time() {
hour = 0;
minute = 0;
second = 0;
std::cout << hour << " " << minute << " " << second << std::endl;
}
this will be called anytime you call Time with the default constructor:
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time t; //<--- this prints 0,0,0
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
system("pause");
return 0;
will result in:
Enter the hour, minute, and second:
11
19
59
0 0 0
11
Press any key to continue . . .
I am also unsure of how to print the time (0,0,0) through the default constructor.
Unless I missing something subtle,
// Construct a Time object using the default constructor.
Time time2;
// Print it's hour
std::cout << time2.getHour() << std::endl;
The code you shared doesn't try to print an object constructed with the default constructor since getHour() is called by time1. The is doing what you tell it to do. If you want the full time from time1you'll have to call all of the getters eg: std::cout << time1.getHour() << " : " << time1.getMinute() << " : " << time1.getSecond() << std::endl
"I am also unsure of how to print the time (0,0,0) through the default constructor."
consider a displayTime() method that can be called on to display the time of any instance
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second); // overloaded constructor
Time time2; // default constructor
// std::cout << time1.getHour() << std::endl;
// std::cout << time2.getHour() << std::endl;
time1.displayTime();
time2.displayTime();
getch();
return 0;
}
add displayTime() method
void Time::displayTime() const{
std::cout << this->hour << ","
<< this->minute << ","
<< this->second << std::endl;
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class TimeUnit
{
public:
TimeUnit(int m, int s)
{
this -> minutes = m;
this -> seconds = s;
}
string ToString()
{
ostringstream o;
o << minutes << " minutes and " << seconds << " seconds." << endl;
return o.str();
}
void Simplify()
{
if (seconds >= 60)
{
minutes += seconds / 60;
seconds %= 60;
}
}
TimeUnit Add(TimeUnit t2)
{
TimeUnit t3;
t3.seconds = seconds + t2.seconds;
if(t3.seconds >= 60)
{
t2.minutes += 1;
t3.seconds -= 60;
}
t3.minutes = minutes + t2.minutes;
return t3;
}
private:
int minutes;
int seconds;
};
int main(){
cout << "Hello World!" << endl;
TimeUnit t1(2,30);
cout << "Time1:" << t1.ToString() << endl;
TimeUnit t2(3,119);
cout << "Time2:" << t2.ToString();
t2.Simplify();
cout << " simplified: " << t2.ToString() << endl;
cout << "Added: " << t1.Add(t2).ToString() << endl;
//cout << " t1 + t2: " << (t1 + t2).ToString() << endl;
/*cout << "Postfix increment: " << (t2++).ToString() << endl;
cout << "After Postfix increment: " << t2.ToString() << endl;
++t2;
cout << "Prefix increment: " << t2.ToString() << endl;*/
}
I'm having problems with my Add method. Xcode is giving me this error: "No matching constructor for initialization of TimeUnit"
Could someone please tell me what I am doing wrong? I've literally tried everything that I know how to do, but I can't even get it to compile with this method.
Here are the instructions from my professor:
The TimeUnit class should be able to hold a time consisting of Minutes
and Seconds. It should have the following methods:
A constructor that takes a Minute and Second as parameters ToString()
- Should return the string equivilant of the time. "M minutes S seconds." Test1 Simplify() - This method should take the time and
simplify it. If the seconds is 60 seconds or over, it should reduce
the seconds down to below 60 and increase the minutes. For example, 2
Min 121 seconds should become 4 minutes 1 second. Test2 Add(t2) -
Should return a new time that is the simplified addition of the two
times Test3 operator + should do the same thing as Add Test4 pre and
postfix ++: should increase the time by 1 second and simplify Test5
In your TimeUnit::Add function, you tried to initialize t3 with default constructor. However, your TimeUnit doesn't have one:
TimeUnit Add(TimeUnit t2)
{
TimeUnit t3; ///<<<---- here
///.....
}
Try update TimeUnit::Add to this way:
TimeUnit Add(const TimeUnit& t2)
{
return TimeUnit(this->minutes+t2.minutes, this->seconds+t2.seconds);
}
The specific problem is because there is no TimeUnit::TimeUnit() defined, only TimeUnit(const int &m, const int &s).
This may be very simple but I am confused!
I am getting segmentation fault when extracting information from a pointer to a pointer. See the cout section in main(). Any help will be appreciated.
Thanks..
Sen
#include <stdlib.h>
#include <iostream>
typedef struct{
int hour;
int minute;
} Time;
Time* GetNextTime(void)
{
Time *p_time = new Time;
return p_time;
}
void GetTime( Time **sometime )
{
int length = 10;
sometime = new Time*[length];
for(int i=0; i<length; i++)
{
sometime[i] = GetNextTime();
sometime[i]->hour = rand()%24 ;
sometime[i]->minute = rand()%60;
std::cout << "Entered times " << sometime[i]->hour << " hour " << sometime[i]->minute << " minutes " << std::endl;
}
}
int main()
{
Time** _time;
GetTime( _time );
//here is the question
// I cant print them from original _time
for( int i=0; i<10; i++)
std::cout << " Print times " << (*_time)[i].hour << " hour " << (*_time)[i].minute << " minutes " << std::endl;
}
You're passing sometime by value, not by reference so it remains uninitialized. Change GetTime to the following:
void GetTime( Time ** &sometime ) //& means pass by reference
Because you're creating an array of pointers, you can use array notation to access them during printing as well.
std::cout << " Print times " << _time[i]->hour << " hour "
<< _time[i]->minute << " minutes " << std::endl;
Unless an argument is explicitly labelled as using a reference it is passed by value in C++. Thus, assigning to sometime in GetTime() has no effect on _time in main().
My strong advice is not to us explict memory allocation but use containers, e.g. std::vector<T>, instead. You'd still need to pass the container by refernence, however.
In main
It should be
Time *_time;
GetTime(&_time)
And then cout should be done with _time instead of *_time
I am making a program in C++ and I wish to print the time at the start and end of the program execution. I have used the following code in main() to output the timestamp at the begining but the values do not update for the end of the program.
I am currently just working procedurally but I am thinking maybe a function would benefit me here.
int main(int argc, char **argv) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
//program execution....
cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
I understand from running the program that it is just using the same values the second time round, how would I go about making this a function?
The value of the 'current' time function is only set with a call to localtime(). The reason you're seeing the same value at the beginning and end of the program is because you've only called that function once. Reset the value of 'now' to time(0), and
'current' to the value of localtime(&now) after program execution, and you'll see the desired update.
To get the time at exit, you just need to repeat the calls to time and localtime.
int main(int argc, char **argv) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
//program execution....
now = time(0);
current = localtime(&now);
cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
You asked about making this a function. I'm not sure that you need to, but if you want to, it might look like this:
void write_timestamp(std::ostream& o, const char *when) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
o << when << ": " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
}
int main(int argc, char **argv) {
write_timestamp(cout, "Examination began at");
//program execution....
write_timestamp(cout, "Examination ended at");
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
localtime only has a one-second resolution, so as #littleadv points out, you would get more accurate results using clock, getrusage, or times. Or, since you're using C++, you might find Boost.Timer useful.
You can get better results by using functions like clock, getrusage or times. Read about these functions here.