C++ Time in seconds problem
#include <iostream> using namespace std;
int main () { int Hour; int Minute; int Second1; int HourSeconds = Hour * 3600; int MinuteSeconds = Minute * 60; int SecondFinal = HourSeconds + MinuteSeconds + Second1;
cout <<"WHat hour is it?" << endl;
cin >> Hour;
cout <<"what minute is it?" << endl;
cin >> Minute;
cout <<"What second is it?" << endl;
cin >> Second1;
system("pause");
cout <<"The time is " << Hour << ":" << Minute << ":" << Second1 << endl;
cout <<"The time in seconds is " << SecondFinal << endl;
system("pause");
return 0;
}
I can not seem to get this to work. No matter what time, it still comes up with the same value of 887918626. please help.
Your setting the values of HourSeconds, MinuteSeconds, and Seconds1 before you get the correct information from the user. You have to do those calculations after you get the user's input.
In C++ the compiler allows you to operate on non initialized variables. The value in those variables is just whatever happens to be in memory when the variables are created. That's why you are getting an answer, but not the answer you're looking for.
+1 to tkearn5000, hit it on the head.
The only other thing I would add to that… Make sure your inputs are a) the correct type and b) the value does not fall otuside the limits of the type you are storing it in.
[ Just stick in some do-while loops in there with some ifs to prompt the user they're being an idiot! :) ]
There are some preprocessor constants with some C and C++ compilers, burried away in the header files, for the upper and lower limits for all the types (unless unsigned).
Jim,
#include <iostream> using namespace std;
int main () { int Hour; int Minute; int Second1; int HourSeconds; int MinuteSeconds; int SecondFinal;
cout <<"WHat hour is it?" << endl; cin >> Hour; cout <<"what minute is it?" << endl; cin >> Minute; cout <<"What second is it?" << endl; cin >> Second1;
HourSeconds=Hour3600; MinuteSeconds=Minute60; SecondFinal=HourSeconds+MinuteSeconds+Second1;
system("pause" ); cout <<"The time is " << Hour << ":" << Minute << ":" << Second1 << endl; cout <<"The time in seconds is " << SecondFinal << endl; system("pause" ); return 0; }