Resolve day of the year c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
i'm new at programming and i'm currently taking C++
I have this code and for example if i'm input 2018 2 32 the output must be 0, but now the output is 62 and i don't know how to resolve this. I need help and wonder if someone can take a look at my code and tell me what is wrong with it?
#include <iostream>
using namespace std;
// pointer
const int january = 31;
const int february = 28;
const int isLeapFeb = 29;
const int march = 31;
const int april = 30;
const int may = 31;
const int june =30;
const int july = 31;
const int august = 31;
const int september = 30;
const int october = 31;
const int november = 30;
const int december = 31;
bool isLeap(int year) {
// menentukan tahun kabisat dan biasa
return (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)));
}
int monthLength(int year, int month, int day) {
// bulan dengan hari 31
if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month || 8) || (month == 10) || (month || 12))
{
if((day > 0) && (day < 32))
return true;
else
return false;
}
// bulan dengan hari 30
if((month == 4) || (month == 6) || (month == 9) || (month == 11))
{
if((day > 0) && (day < 31))
return true;
else
return false;
}
if(month == 2) // februari 28 hari
{
if((day > 0) && (day < 29))
return true;
else
return false;
}
if((isLeap(year))) // februari 29 hari
{
if((month == 2) && ((day > 0) && (day < 30)))
return true;
else
return false;
}
}
int dayOfYear(int year, int month, int day) {
// tahun 1582 Gregorian kalender mulai
int dayTotal = 0;
if(monthLength(year, month, day))
{
if(month == 1)
{
dayTotal = 0 + day;
}
if(month == 2)
{
dayTotal = january + day;
}
if((month == 3) && (year > 1582))
{
dayTotal = january + february + day;
if((month == 3) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + day;
}
}
if((month == 4) && (year > 1582))
{
dayTotal = january + february + march + day;
if((month == 4) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + day;
}
}
if((month == 5) && (year > 1582))
{
dayTotal = january + february + march + april + day;
if((month == 5) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + day;
}
}
if((month == 6) && (year > 1582))
{
dayTotal = january + february + march + april + may + day;
if((month == 6) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + day;
}
}
if((month == 7) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + day;
if((month == 7) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + day;
}
}
if((month == 8) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + day;
if((month == 8) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + july + day;
}
}
if((month == 9) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august + day;
if((month == 9) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + july + august + day;
}
}
if((month == 10) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august + september + day;
if((month == 10) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + july + august + september + day;
}
}
if((month == 11) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august + september + october + day;
if((month == 11) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + july + august + september + october + day;
}
}
if((month == 12) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august + september + october + november + day;
if((month == 5) && (year > 1582) && (isLeap(year)))
{
dayTotal = january + isLeapFeb + march + april + may + june + july + august + september + october + november + day;
}
}
}
return dayTotal;
}
int main(void) {
int day, month, year;
cout << "Enter year month day: ";
cin >> year >> month >> day;
cout << dayOfYear(year, month, day) << endl;
return 0;
}
It compile but the output is not correct. I really appreciate your help and feedback. Thank you very much

That is because your are passing days as 31 and when this line executed:
if(month == 2)
{
dayTotal = january + day;
}
Then
dayTotal = 31 + 31; // = 62 which is what you see.
You need to use the debugger to discover such errors, beside you need to add some validations to prevent invalid data such as 02/31/2018

EDIT:
Based on suggestions from #Slava, I have revised my answer. This implementation uses a single regular expression match to validate and to extract the components of the date. Here is the code:
#include <iostream>
#include <string>
#include <regex>
#include <exception>
using namespace std;
void parseDate(const string& date, int& year, int& month, int& day)
{
regex dateValidateRe(R"(^(\d{4})\-(\d{1,2})\-(\d{1,2})$)");
smatch matches;
if (!regex_search(date, matches, dateValidateRe))
{
throw invalid_argument("Date format is incorrect");
}
year = stoi(matches[1]);
month = stoi(matches[2]);
day = stoi(matches[3]);
}
int main()
{
int year, month, day;
string date;
cin >> date;
try
{
parseDate(date, year, month, day);
}
catch (std::exception& ex)
{
cout << "Invalid input: " << ex.what() << endl;
}
cout << "The date entered was Year = " << year << " Month = " << month << " Day = " << day << endl;
return 0;
}
Here is a working demo
** Original Response **
You're not parsing your input correctly. Your input is 2018-2-31 is being parsed as year 2018, month -2, and day -31. You need to parse your date as a string and then break that string apart by the token - to extract year, month, and day.
Here is a quick and dirty function that you can use to parse the input correctly:
void parseDate(const string& date, int& year, int& month, int& day)
{
auto ypos = date.find("-");
string syear = date.substr(0, ypos);
auto mpos = date.find("-", ypos+1);
string smonth = date.substr(ypos+1, mpos-ypos-1);
string sday = date.substr(mpos+1);
year = stoi(syear);
month = stoi(smonth);
day = stoi(sday);
}
Update your main as follows:
int main(void) {
int day, month, year;
cout << "Enter year month day: ";
string date;
cin >> date;
parseDate(date, year, month, day);
cout << dayOfYear(year, month, day) << endl;
return 0;
}
This should give you the right results. Please update parseDate so it validates the input string before it proceeds to tokenize it.

Related

the Date class i wrote crashes when i call parameterized constructor but runs cool when default constructor runs

this is default constructor
Date::Date():day(1), month(1), year(1990){
}
this is parameterized
Date::Date(int day, int month, int year){
this->day = dayTest(day);
this->month = monthTest(month);
this->year = yearTest(year);
}
when i try to call parameterized constructor like this:
Date obj(12, 12, 1900); //dd/mm/yyyy
the program crashes, here is the full code:
#include <iostream>
#include "Date.h"
using namespace std;
Date::Date():day(1), month(1), year(1990){
}
Date::Date(int day, int month, int year){
this->day = dayTest(day);
this->month = monthTest(month);
this->year = yearTest(year);
}
void Date::setDay(int day){
this->day = dayTest(day);
}
void Date::setMonth(int month){
this->month = monthTest(month);
}
void Date::setYear(int year){
this->year = yearTest(year);
}
int Date::dayTest(int day){
const int totalDaysInMonths[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31};
if(day > 0 && day <= totalDaysInMonths[month])
return day;
if(month == 2 && day == 29 && ((year % 4 == 0 && year % 100 != 0) || year %
400 ==0))
return day;
else
return 1;
}
int Date::monthTest(int month){
if(month > 0 && month <= 12){
return month;
}else{
return 1;
}
}
int Date::yearTest(int year){
if(year >= 1900 && year <= 2050){
return year;
}else{
return 1990;
}
}
void Date::printDate()const{
cout << day << "/" << month << "/" << year;
}

C++ Month, day, and year validation

I'm currently working on a project for my intro to C++ programming class. The project asks a user to enter a date using mm/dd/yyyy format. Based on the information given, the program then has to determine if the date is valid or invalid, then displays a response to that. I'm facing the problem currently where everything is coming out reading "Good date!" I'm not sure where the problem is. Any help is appreciated. If you could help point me in the right direction, that would be awesome.
#include <iostream>
#include <conio.h>
using namespace std;
void getDate(int *month, int *day, int *year);
int checkDate(int month, int day, int year);
void displayMessage(int status);
int main()
{
int month, day, year;
int s = 0;
getDate(&month, &day, &year);
do
{
checkDate(month, day, year);
displayMessage(s);
getDate(&month, &day, &year);
}
while (_getch() != EOF);
}
void getDate(int *month, int *day, int *year)
{
char fill;
fill = '/';
cout << "Enter a date in mm/dd/yyyy form: ";
cin >> *month;
if (cin.get() != '/')
{
cout << "expected /" << endl;
}
cin >> *day;
if (cin.get() != '/')
{
cout << "expected /" << endl;
}
cin >> *year;
cout << *month << fill << *day << fill << *year << endl;
};
int checkDate(int month, int day, int year)
{
if ((month = 1) || (month = 3) || (month = 5) || (month = 7) ||
(month = 8) || (month = 10) || (month = 12))
{
day <= 31;
}
else if ((month = 4) || (month = 6) || (month = 9) || (month = 11))
{
day <= 30;
}
else if ((month = 2) && (year % 4 == 0))
{
day <= 29;
}
else if ((month = 2) && (year % 4 != 0))
{
day <= 28;
};
int status = 0;
if ((year < 999) || (year > 10000))
{
status == 1;
}
if ((month < 1) || (month > 12))
{
status == 2;
}
else if ((day < 1) || (day > 31))
{
status == 3;
}
else if ((day < 1) || (day > 30))
{
status == 4;
}
else if ((day < 1) || (day > 29))
{
status == 5;
}
else if ((day < 1) || (day > 28))
{
status == 6;
}
return status;
};
void displayMessage(int status)
{
if (status == 0)
{
cout << "Good date!" << endl;
}
if (status == 1)
{
cout << "Bad year" << endl;
}
if (status == 2)
{
cout << "Bad month" << endl;
}
if (status == 3)
{
cout << "Bad day. Not 1-31" << endl;
}
if (status == 4)
{
cout << "Bad day, not 1-30" << endl;
}
if (status == 5)
{
cout << "Bad day, not 1-29" << endl;
}
if (status == 6)
{
cout << "Bad day, not 1-28" << endl;
}
_getch();
}
1) There are a couple of issues here, but the most obvious one is in main():
int s=0;
...
checkDate(month, day, year); // you don't store the status
displayMessage(s); // so s will always be 0 ! So good date !
You have to correct this:
s=checkDate(month, day, year); // store the result of the check
displayMessage(s); // and take it to display the message
2) Then in checkDate(), you mixup = and ==. = changes the value of the variable to its left. == just makes a comparison but store nothing. When correcting/adjusting, without any optimisation, your code should look like:
int checkDate(int month, int day, int year)
{
int status=0;
if ((month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12) && ( day>31 || day<1) )
{
status = 3;
}
else if ((month == 4 || month == 6 || month == 9 || month == 11) && (day>30 || day<1) )
{
status = 4;
}
else if ((month == 2) && (year % 4 == 0) && (day>29 || day<1))
{
status = 5;
}
else if ((month == 2) && (year % 4 != 0) && (day>28 || day<1) )
{
status = 6;
}
else if ((year < 999) || (year > 10000))
{
status = 1;
}
if ((month < 1) || (month > 12))
{
status = 2;
}
return status;
};
3) After this, you should improve the input function, because:
it doesn't cope with invalid separators. If '/' are missing, an error message is displayed, but you continue the input as if everything was fine.
it doesn't cope with invalid (i.e.non numeric) input. If user enters XI/1/2016 for example, your input will fail.
So keep in mind that (cin>>xxx) is an expression that you could use in an if and is true if everything was read correctly. Also be aware that cin.clear() clears error flags that blocks input after a failure.
You also could make use of the function mktime().
It tries to convert a given tm struct into a correct date. If the comparison of the individual members of the struct subsequently shows equality for all members, the given tm struct contained a valid date.
bool CBorrow::validateDate(tm * timestruct)
{
struct tm copy;
copy.tm_sec = timestruct->tm_sec;
copy.tm_min = timestruct->tm_min;
copy.tm_hour = timestruct->tm_hour;
copy.tm_mday = timestruct->tm_mday;
copy.tm_mon = timestruct->tm_mon;
copy.tm_year = timestruct->tm_year;
copy.tm_wday = timestruct->tm_wday;
copy.tm_yday = timestruct->tm_yday;
copy.tm_isdst = timestruct->tm_isdst;
time_t res = mktime(&copy);
if (res < 0)
{
return false;
}
if (copy.tm_mday != timestruct->tm_mday
|| copy.tm_mon != timestruct->tm_mon
|| copy.tm_year != timestruct->tm_year)
{
return false;
}
return true;
}
Updated answer for C++20:
#include <chrono>
#include <iostream>
void
displayMessage(std::chrono::year_month_day ymd)
{
using namespace std;
using namespace std::chrono;
if (!ymd.year().ok())
{
cout << "Bad year\n";
return;
}
if (!ymd.month().ok())
{
cout << "Bad month\n";
return;
}
if (!ymd.ok())
{
cout << "Bad day, not 1-" << (ymd.year()/ymd.month()/last).day() << '\n';
return;
}
cout << "Good date!\n";
}
int
main()
{
using namespace std::literals;
displayMessage(29d/2/1900);
}
Output:
Bad day, not 1-28
(1900 was not a leap year)
Can this also be achieved by a regular expression?
I know there are many drawbacks in this approach, but still may be considered:
#include <regex>
#include <string>
using std::regex;
using std::regex_match;
using std::string;
// for ddmmyy
regex ddmmyy("^([0-2][0-9]|(3)[0-1])(((0)[0-9])|((1)[0-2]))\\d{2}$");
/*
for dd/mm/yy https://regex101.com/r/IqPLBJ/1
for dd/mm/yyyy - could start from \\d{4}$ instead of \\d{2}$ bearing 0000-case in mind
*/
regex slashed_ddmmyy("^([0-2][0-9]|(3)[0-1])\/(((0)[0-9])|((1)[0-2]))\/\\d{2}$");
string f1 = "111223";
bool res = regex_match(f1,ddmmyy); // true
f1 = "112223";
res = regex_match(f1,ddmmyy); // false
res = regex_match(f1, slashed_ddmmyy); // false, no slashes
A more compact and stripped checkDate (replace uppercase return by value)
int checkDate(int day, int month, int year) {
if(day < 1 || day > 31) {
return BADVALUE;
} else if(month < 1 || month > 12) {
return BADVALUE;
} else if (year < MINYEAR || year > MAXYEAR) {
return YEAROUTRANGE;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
return BADMONTHDAY;
} else if ((month == 2) && (year % 4 == 0) && day > 29) {
return BADMONTHYEAR;
} else if ((month == 2) && (year % 4 != 0) && day > 28) {
return BADMONTHYEAR;
}
return GOOD;
}

Control may reach end of non-void function (checking for valid date)

bool isValidDate(int month, int day, int year) {
if(year <= 1752){
if(month <= 9 && month <= 13){
return false;
}
else{
}
}
else{
if((month == 9 || month == 4 || month == 6 || month == 11) && (day <= 30)){
return true;
}
else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day <= 31)){
return true;
}
else if(isLeapYear(year)){
if((month == 2) && (day <= 29)){
return true;
}
}
else if(!isLeapYear(year)){
if((month == 2) && (day <= 28)){
return true;
}
}
else{
return false;
}
}
}
I'm trying to make it so that if users enter any date before Sept. 13, 1752, it will return false. And also if the days have to be correct according to the month while taking into account leap years for the month of February. But I keep getting an error. Help much needed.

calculate the day of the year c++

I'm new in programming and I'm currently taking C++.
For example, if the year entered is below 1583, but month and day value is within range, then the program will display error message. However, if the year value is above 1582, but the month or the day value is out of range, then it will still proceed to calculate the day of the year.
here is my code
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
void showOption();
bool validMonth (int month);
bool validYear (int year);
bool leapYear (int year);
bool validDay (int year, int month, int day);
void getData (int& month, int& day, int& year);
void easterDate (int& month, int& day, int& year);
int daysBetween (int month1, int day1, int month2, int day2, int year);
int dayOfYear (int day, int month, int year);
const int january = 31;
const int february = 28;
const int leapYearFeb = 29;
const int march = 31;
const int april = 30;
const int may = 31;
const int june =30;
const int july = 31;
const int august = 31;
const int september = 30;
const int october = 31;
const int november = 30;
const int decemebr = 31;
int main()
{
int option;
int day, month, year;
int easterDay, easterMonth;
int day1, day2, month1, month2;
bool repeat = false;
showOption();
cout << "please enter your option: ";
cin >> option;
cout << "" << endl;
switch (option)
{
case 1:
do
{
getData(month, day, year);
validDay(year, month, day);
if(validDay(year, month, day) == true)
{
cout << "month " << month << " day " << day << " year " << year << endl;
cout << " " << endl;
cout << "They day of the year based on the date you entered is "<< dayOfYear(day, month, year) << endl;
cout << " " << endl;
}
else
{
cout << "it is not a valid date." << endl;
}
cout << "do you still want to continue?" << endl;
cout << "0 = no. 1 = yes. ";
cin >> repeat;
cout << " " << endl;
} while(repeat);
break;
case 2:
do
{
cout << "do you still want to continue?" << endl;
cout << "0 = no. 1 = yes. ";
cin >> repeat;
} while(repeat);
break;
case 3:
do
{
cout << "do you still want to continue?" << endl;
cout << "0 = no. 1 = yes. ";
cin >> repeat;
} while(repeat);
break;
}
}
void showOption()
{
cout << " ------------------MENU------------------ " << endl;
cout << " 1) Day of the year." << endl;
cout << " 2) Date of Easter day." << endl;
cout << " 3) Number of days between 2 days entered." << endl;
cout << "" << endl;
cout << "" << endl;
}
bool validMonth (int month)
{
if (month > 0 || month < 13)
return true;
else
return false;
}
bool validYear (int year)
{
if (year > 1582)
return true;
else
return false;
}
bool leapYear (int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return true;
else
return false;
}
void getData (int& month, int& day, int& year)
{
cout << "enter the number of year: ";
cin >> year;
cout << "" << endl;
cout << "enter the number of month: ";
cin >> month;
cout << "" << endl;
cout << "enter the number of day: ";
cin >> day;
cout << "" << endl;
}
bool validDay (int year, int month, int day)
{
if(year > 1582)
{
if(validMonth(month))
{
if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month || 8) || (month == 10) || (month || 12))
{
if((day > 0) || (day < 32))
return true;
else
return false;
}
if((month == 4) || (month == 6) || (month == 9) || (month == 11))
{
if((day > 0) || (day < 31))
return true;
else
return false;
}
if(month == 2)
{
if((day > 0) || (day < 29))
return true;
else
return false;
}
if((leapYear(year)))
{
if((month == 2) && ((day > 0) || (day < 30)))
return true;
else
return false;
}
}
}
}
int dayOfYear (int day, int month, int year)
{
int dayTotal = 0;
if(validDay(year, month, day))
{
if(month == 1)
{
dayTotal = 0 + day;
}
if(month == 2)
{
dayTotal = january + day;
}
if((month == 3) && (year > 1582))
{
dayTotal = january + february + day;
if((month == 3) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + day;
}
}
if((month == 4) && (year > 1582))
{
dayTotal = january + february + march + day;
if((month == 4) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + day;
}
}
if((month == 5) && (year > 1582))
{
dayTotal = january + february + march + april + day;
if((month == 5) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + day;
}
}
if((month == 6) && (year > 1582))
{
dayTotal = january + february + march + april + may + day;
if((month == 6) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + day;
}
}
if((month == 7) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + day;
if((month == 7) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + day;
}
}
if((month == 8) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + day;
if((month == 8) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + july + day;
}
}
if((month == 9) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august
+ day;
if((month == 9) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + july + august
+ day;
}
}
if((month == 10) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august
+ september + day;
if((month == 10) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + july + august
+ september + day;
}
}
if((month == 11) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august
+ september + october + day;
if((month == 11) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + july + august
+ september + october + day;
}
}
if((month == 12) && (year > 1582))
{
dayTotal = january + february + march + april + may + june + july + august
+ september + october + november + day;
if((month == 5) && (year > 1582) && (leapYear(year)))
{
dayTotal = january + leapYearFeb + march + april + may + june + july + august
+ september + october + november + day;
}
}
}
return dayTotal;
}
It compile but the output is not correct.
Question:
I need help and wonder if someone can take a look at my code and tell me what is wrong with it?
Note: I have been working in this code for 2 days and I cant figure out what I did wrong. I really appreciate your help and feedback. Thank you very much
You're using many disjunctions ("or", ||) where you should use conjunctions ("and", &&).
For instance, month > 0 || month < 13 is true for a month of -10 or 1432.
There are also some places where a || should be ==.
Month length implement as
const int month_lenght [ 31,28,31 ... ];
Warning: january here==0, that problem is present in Java Date january=0 but day 1=first. So alternative can be:
const int month_lenght [ 0 /*dummy*/ 31,28,31 ... ];
then no
if(month == 1)
{
dayTotal = 0 + day;
}
if(month == 2)
{
dayTotal = january + day;
}
but for loop.
if is required only for February and leap year
EDIT: agree, errors with && and ||
EDIT2:
probably
void easterDate (int& month, int& day, int& year);
change declaration, maybe to:
void easterDate (int& month /* out */, int& day /*out */ , int year /* in */);
BTW all world except english-USA culture think (and compute) y/m/d or d/m/y

Variable not initialized in C++ code?

Edit: Thank you all very much for your answers, I know now that this was a stupid question, but I've been attempting to get into C++ after just getting a handle on Visual Basic, so a lot of these things I am unfamiliar with. I promise I'm not just asking them to waste your time.
I've been trying to do a sample project in C++ to learn the basics, and I'm having an issue with the current code. The program is supposed to add up user inputted variables and take into account which month they have entered to apply different charges. However, It says that my variable, usageCost, hasn't been initialized. Here's the code:
#include <iostream>
using namespace std;
int main()
{
string monthtext;
double month,
days,
hours,
kwhr,
completeCharge,
energyadjustCharge;
const double flatservicecharge = 5.31;
cout << "Enter the month (1-12) :";
cin >> month;
cout << "Number of days in the period :";
cin >> days;
cout << "Kilowatt hours used :";
cin >> hours;
if (month = 1){
monthtext = "January";
}
else{
if (month = 2){
monthtext = "February";
}
else{
if (month = 3){
monthtext = "March";
}
else{
if (month = 4){
monthtext = "April";
}
else{
if (month = 5){
monthtext = "May";
}
else{
if (month = 6){
monthtext = "June";
}
else{
if (month = 7){
monthtext = "July";
}
else{
if (month = 8){
monthtext = "August";
}
else{
if (month = 9){
monthtext = "September";
}
else{
if (month = 10){
monthtext = "October";
}
else{
if (month = 11){
monthtext = "November";
}
else{
if (month = 12){
monthtext = "December";
}
}
}
}
}
}
}
}
}
}
}
}
double usageCost;
if (month <= 5 && month >= 10 && hours <= 500){
usageCost = hours * 12.9266;
}
if (month <= 5 && month >= 10 && hours > 500){
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
if (month >= 6 && month <= 9 && hours <= 750){
usageCost = 750 * 12.9266;
}
if (month >= 6 && month <= 9 && hours > 750){
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
energyadjustCharge = hours * .1305;
completeCharge = usageCost + flatservicecharge + energyadjustCharge;
cin.get();
return 1;
}
You declare:
double usageCost;
but as you can see, you don't set it to any value, thus it is unintialized.
Compiler is correct.
Solution:
Try:
double usageCost = 0.0;
Edit 1:
Other Issues with your program:
Assignment uses "=", comparison uses "=="
Please change all your if statements accordingly.
Replace if statements with array lookup
Adding the following will simplify your program:
const std::string month_names[] =
{"No month index 0",
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
// ...
month_text = month_names[month];
The error is because you have some code paths that never set usageCost. Rather than hide the error by initializing usageCost, it is better to fix your code which surely did intend to give usageCost a value in all cases.
In fact it is good that you didn't initialize usageCost because it meant you got a compiler warning to alert you to the later logic error.
month <= 5 && month >= 10 is never true. No month is before June and also after September. You probably meant (month <= 5 || month >= 10). The brackets are important because you have another && condition following.
However it would be better to avoid code duplication and avoid the possibility of none of the four cases being entered by rewriting that section:
if ( month >= 6 && month <= 9 )
{
if ( hours > 750 )
usageCost = ......;
else
usageCost = ......;
}
else
{
if ( hours > 500 )
usageCost = ......;
else
usageCost = ......;
}
With this structure it is impossible for usageCost to not be assigned something.
You have defined month to be a double.
double month;
cout << "Enter the month (1-12) :";
cin >> month;
If I type 5.5 for this input, you can see that usageCost will never be initialized to any value.
double usageCost;
// This will evaluate to false
if (month <= 5 && month >= 10 && hours <= 500){
usageCost = hours * 12.9266;
}
// This will evaluate to false
if (month <= 5 && month >= 10 && hours > 500){
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
// This will evaluate to false
if (month >= 6 && month <= 9 && hours <= 750){
usageCost = 750 * 12.9266;
}
// This will evaluate to false
if (month >= 6 && month <= 9 && hours > 750){
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
Consider:
Initializing usageCost to a default value
using an int or similar for values that will only ever be "whole numbers".
using month > 5 as the true inverse of month <= 5
I fixed a number of issues for you.
#include <iostream>
using namespace std;
int main()
{
string monthtext;
double month,
days,
hours,
kwhr,
completeCharge,
energyadjustCharge;
const double flatservicecharge = 5.31;
cout << "Enter the month (1-12) :";
cin >> month;
cout << "Number of days in the period :";
cin >> days;
cout << "Kilowatt hours used :";
cin >> hours;
struct {int input; string month;} Calendar[] = {
{ 1, "January" },
{ 2, "February" },
{ 3, "March" },
{ 4, "April" },
{ 5, "May" },
{ 6, "June" },
{ 7, "July" },
{ 8, "August" },
{ 9, "September" },
{ 10, "October" },
{ 11, "November" },
{ 12, "December" } };
for(int i = 0; i < ARRAY_SIZE(Calendar); ++i)
{
if (month == Calendar[i].input)
{
monthtext = Calendar[i].month;
break;
}
}
double usageCost = 0.0;
if (month <= 5 && month >= 10 && hours <= 500)
{
usageCost = hours * 12.9266;
}
if (month <= 5 && month >= 10 && hours > 500)
{
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
if (month >= 6 && month <= 9 && hours <= 750)
{
usageCost = 750 * 12.9266;
}
if (month >= 6 && month <= 9 && hours > 750)
{
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
energyadjustCharge = hours * .1305;
completeCharge = usageCost + flatservicecharge + energyadjustCharge;
cin.get();
return 0;
}