Variable not initialized in C++ code? - c++

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;
}

Related

Why are all of my booleans setting off as true?

I tested my code out by printing the values out to see why it did not output the value I should be getting. And I found out all of my booleans that were for the string ride were set off as true and I can not seem to get a clue why. I have tried searching the internet up yet I could not find anything. My understanding of the code is not deep enough for me to understand what is going wrong here.
#include <iostream>
#include <string>
using namespace std;
int main() {
//declarations
string ride;
char comp;
int age;
double td, tp, god, rp, sp, ta, tap;
bool fer, bump, zip, pir, test;
//print outs and input
cout<<"What ride would you like to buy a ticket for? "<<endl;
getline(cin, ride);
cout<<"How old are you?"<<endl;
cin>>age;
//functions
//ride
if (ride == "Ferris Wheel"){
rp = rp + 75.00;
fer = true;
}
if (ride == "Bumper Cars"){
rp = rp + 50.00;
bump = true;
}
if (ride == "Zipper"){
rp = rp + 100.00;
zip = true;
}
if (ride == "The Pirate Ship"){
rp = rp + 75.00;
pir = true;
}
//age
//ferris wheel
if (fer = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
}
//bumper car
if(bump = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
else if(age > 60){
td = td + .20;
}
}
//zipline
if (zip = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
td = td + 0.10;
}
// pirate ship
if (pir = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
}
// maths jaajbjabjabjaj B(
cout<<fer<<endl;
cout<<bump<<endl;
cout<<zip<<endl;
cout<<pir<<endl;
cout<<td<<endl;
cout<<rp<<endl;
cout<<td<<endl;
god = rp * td;
cout<<"discount computed: "<<god<<endl;
sp = rp - god;
cout<<"sub pirce jajagnkfgdf: "<<sp<<endl;
tap = sp * 0.05;
cout<<"tap: "<<tap;
ta = sp + tap;
cout<<"ta: "<<ta;
}
input for ride: The Pirate Ship
input for age: 9
output i get from code:
discount i get from code: 30
partial price : 45
total price : 47.25
output i should be getting from code:
discount i get from code: 7.5
partial price : 67.5
total price : 70.875
I think this is because you didn't initialize your boolean variables. There is no single line, where you set "false". So that, they get random values, i.e. any non-zero value is considered as "true".
Set default value for booleans bool fer = false, bump = false, zip = false, pir = false, test = false;
You are using if wrong.
if (zip = true) // if zip equals true.
if (zip == true) // if zip equals true?
Use else if
//ride
if (ride == "Ferris Wheel"){
rp = rp + 75.00;
fer = true;
}
else if (ride == "Bumper Cars"){
rp = rp + 50.00;
bump = true;
}...
The ride cannot equal "Ferris Wheel" and "Bumper Cars" same time.

Multiplying by a decimal wont give me a decimal answer to feed back into my variable

Currently using Clion to work on a homework question. I believe i am using my if-statements correctly, as-well as the double and char but it doesn't seem to be giving me the outcome i seek. The question asks:
Buy one get one half off promotion: the lower price item is half price.
If the customer is club card member, additional 10% off.
Tax is added.
I have tried to move brackets around. I have declared the .90 to a set variable and tried multiplying that but still always gives me the same answer. I think it has something to do with my if-statemets.
using namespace std;
int main() {
double price1, price2, taxRate, fullSubtotal;
char clubCard;
double basePrice, cardPrice, finalPrice;
// ...
cout<<"Enter price of first item: ";
cin>>price1;
cout<<"Enter price of second item: ";
cin>>price2;
cout<<"Does customer have a club card? (Y/N): ";
cin>>clubCard;
cout<<"Enter tax rate, e.g. 5.5 for 5.5% tax: ";
cin>>taxRate;
fullSubtotal = price1 + price2;
taxRate /= 100;
taxRate += 1;
if (price1 > price2) {
price2 /= 2.00;
basePrice = price1 + price2;
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else (clubCard == 'n' || clubCard == 'N'); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
else {
price1 /= 2.00;
basePrice = price1 + price2;
if ((clubCard == 'y') || (clubCard == 'Y')) {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else ((clubCard == 'n') || (clubCard == 'N')); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
cout<<"Base price: "<<fullSubtotal<<endl;
cout<<"Price after discounts: "<<cardPrice<<endl;
cout<<"Total price: "<<finalPrice<<endl;
return 0;
}
Each time i enter the values for each price( 10 and 20), it gives me the correct fullSubtotal, but when i seek the corresponding cardPrice for that route (if-statement), it gives me 25. With a total price (including tax) to be 27.0625. I was expecting the output to be, cardPrice: 22.5 with finalPrice: 24.35625
Your problem is in the else sections:
if(clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
} else
(clubCard == 'n' || clubCard == 'N');
{
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
The condition you tried to add for the else becomes a statement and the code in the {} block after overwrites the values you previously set. Fix:
if(clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
} else if(clubCard == 'n' || clubCard == 'N') {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
Your mistake is at the inner else clause.
An else-clause has no condition, so the (clubCard == 'n' || clubCard == 'N'); is useless, but still correct c++. It evaluates to a bool that is then discarded. The problem is, that the the block after this is always executed, because it has no condition anymore.
Either use else if and drop the semicolon or just drop the whole condition and the semicolon:
...
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
....

c++ bad access error on find()

I am getting a bad access error while trying to find days between two dates given as a string. I found that the maximum number of days that my function will find is 1884 but I don't know why. The bad access error is in the a.find("/") function call.
Here is the code. Any help would be much appreciated, thanks.
int daysBetweenDates(string a, string b) {
if (a == b) {
return 0;
}
cout << a << endl;
int month = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int day = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int year = stoi(a);
int k = 0; // days in the month;
if (month == 2) {
k = year%4==0 ? 29 : 28;
}
else if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
k = 30;
}
else {
k = 31;
}
day++;
if (day > k) {
month++;
day = 1;
}
if (month > 12) {
year++;
month = 1;
}
string new_a = to_string(month) + "/" + to_string(day) + "/" + to_string(year);
return 1 + daysBetweenDates(new_a, b);
}
The recursive calls are eventually causing a stack overflow. Change the code to remove the potentially deeply nested calls. For example, by changing the routine to use a loop. C++ compilers typically do not do tail recursion optimization.

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;
}

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