I have to write a program for a C++ class and I am having a bit of trouble. I have gone through all my variables and I feel like I initialized everything, but its still not working.
Program parameters: Calculate electrical bill. Customer gets charged $0.27 a kwh up to 500 kwh, then is charged at an extra rate of $0.57 a kwh thereafter.
Input: kwh
output: Total customer bill
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//List the variables
double kwh;
double baseKwh;
double extraKwh;
double baseBill;
double extraBill;
double electricBill;
//User inputs the kwh used
cout << "Enter kwh used: "; //Prompt
cin >> kwh;
//Process the data and compute the bill
if (kwh <= 500) {
baseKwh = kwh;
extraBill = 0;
}
else {
baseKwh = 500;
extraKwh = kwh - 500;
}
baseBill = baseKwh * 0.27;
extraBill = extraKwh * 0.55;
electricBill = baseBill + extraBill;
//Output the bill.
cout << "Your bill is $" << electricBill << endl;
system("PAUSE");
return 0;
}
problem:
Run-Time Check Failure #3 - The variable 'extraKwh' is being used
without being initialized.
Microsoft Visual Studio points to line 30 as the problem. The program works fine when the user inputs above 500, however, when the user inputs 500 or below then I get the error message.
extraBill = extraKwh * 0.55;
Well if the else clause is not evaluated above this code, extraKwh is indeed uninitialized. So you are trying to read value of uninitialized variable above and triggering undefined behaviour. Assign some default value to it during declaration and that issue should go away.
In general it is good idea to initialize variables during declaration.
You have declared your variables, but left them uninitialized.
You are using extraKwh no matter what happens in your code. Judging by your logic, you should initialize it to zero at the same time it is declared:
double extraKwh = 0;
This way, there will always be a value assigned to extraKwh, even if you don't don't hit your else block.
Related
I have been trying to write a simple code in C++ to calculate CGPA. It is a practice code. There is no error in code when I start to build. But it is not running.
I am using codeblocks. I have checked everything. but can not find any problems in it.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int g,h,i,a=0, grade[g],hour[h];
char course[10];
float z=0,sum =0, result=0, totalhour=0;
cout<<"How Many Course's do you want to calculate for CGPA: ";
cin>> a;
cout<<endl;
cout<<"Please Enter your Course name, Credit hour & Grade point of the your course"<<endl;
for(i=1;i<=a;i++)
{
cout<<i<<". no Course name: ";
cin>>course[i];
cout<<"-----";
cout<<"Credit Hour: ";
cin>>hour[h];
cout<<"-----";
cout<<"Grade point: ";
cin>>grade[g];
cout<<"\n";
}
for (i=1; i<=a;i++)
{
cout<<i<<".no Course----";
z= grade[g]*hour[h];
cout<<"Grade point X Credit Hour = "<<grade[g]<<" X "<<hour[h]<<" = "<<z<<endl;
sum = sum+z;
totalhour= totalhour+hour[h];
}
result = sum / totalhour;
cout<<"Your total Credit hour Completed is : "<<totalhour<<endl;
cout<<"----Your Total CGPA is -------- = "<<result<<endl;
getch();
return 0;
}
You have some problems in your code:
What happens if user input is larger then 10? you assume it will be smaller (you will get undefined behavior since the array size is 10, and your for loop runs until user input)
int g,h,i,a=0, grade[g],hour[h]; - what is the size of grade and hour? you can not "dynamically" give them a size. You must tell what size they are when you declare them, unless you use dynamic containers such as std::vector.
I am currently working on a prototype payroll system.
Every time I put the required information for the calculations, it always outputs the wrong information (I always check with a calculator).
It doesn't have any errors or warnings so I think the problem is how I format the code.
Can someone please teach me how to fix this problem?
Note: The program is incomplete.
#include <iostream>
#include <vector>
#include <fstream>
#ifdef _WIN32
#include <windows.h>
#define SYSERROR() GetLastError()
#else
#include <errno.h>
#define SYSERROR() errno
#endif
struct Employees//Not in use yet
{
std::string first_name;
std::string last_name;
};
class Salary_variables
{
public:
long days = 0;
long overtime = 0;
long basic_pay = 537;
long overtime_pay = 80.1375;
long regular_salary = days * basic_pay;
long compute()//constructor for determining the employee's salary
{
if (overtime == 0)
{
return regular_salary;
}
else if (overtime >= 0)
{
long overtime_salary = overtime * overtime_pay;
return regular_salary + overtime_salary;
}
}
};
int main()
{
Employees employee;
std::cout << "Type in employee's full name:\n";
std::cin >> employee.first_name >> employee.last_name;
Salary_variables variables;
std::cout << "Type in total amount of days worked:\n";
std::cin >> variables.days;
std::cout << "Type in total amount of overtime hours worked:\n";
std::cin >> variables.overtime;
std::cout << "Total salary: " << variables.compute() << "\n";
return 0;
}
I can see 2 big mistakes in your code, but without examples of input and output it is possible I missed more.
The biggest error is that you are using long - which is an integer type!
You need to use double so that the decimal part of the salary will be preserved in the calculation.
For example, using long 10 hours of overtime would be worth 80 * 10 = 800.
But, with the correct calculation using double, 80.1375 * 10.0 = 801.375.
Also, as others already mentioned, you must do the multiplication inside the compute function.
Member variable initialization happens only once when you create an instance of the class.
So your code multiplies the salary by 0 on line Salary_variables variables;.
If you change the days variable afterwards, nothing will happen.
The below initialization should be done inside compute function:
long regular_salary = days * basic_pay;
Otherwise, it will initialize the variable with default values when creating class variable.
I am trying to build a program that outputs No. of people I have entered and the average of their ages. This is my code
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age;
int total = 0;
int No_of_People = 0;
while (age != -1){
total = total + age;
No_of_People++;
cout << "Enter a person's age or enter -1 to stop\n";
cin >> age;
}
cout << "Number of people entered:\n" <<No_of_People<< endl;
cout << "Average age of people = "<< total/No_of_People;
return 0;
}
However the computer prints the average wrong, anyone know what i did wrong?
This is the output
I see two major problems in your code: First, age is not initialized. Reading from it leads to undefined behavior (as mentioned by UnholySheep). Everything could happen from some seemingly random value to an access violation. I once forgot to initialize a boolean variable, it was initialized with false on my computer every time I ran the program (like I intended), on another team members it was initialized to true and we wondered why it's working for me but not for him. So best initialize it with 0 like you do for total.
Second, you're adding age on total before knowing its value. So when you set age to 0 in the beginning, you will increase the number of people one more time than you increase the total age. Add age to total after asking for a value.
A third thing is, that you don't take care for -1 properly. You're increasing the number of people even if -1 is typed in. You should check for that value before increasing the number of people or adding it to your total.
Just thought I would add to Tobias Brösamle's answer.
A good hint that you did not initialize age might be that running the program multiple times with the same input values yields different results.
Have a look at these modifications, comments highlight changed code.
Mostly I see that you're a beginner in coding, your errors can be attributed to not quite developing a "working methodology" - i.e. always initialising variables. I also moved the code into a separate function, whenever I put test code in a main function it very quickly develops into needing to do this anyway.
#include <string>
#include <iostream>
using namespace std;
void age()
{
int age = 0; // not initalised
int total = 0;
int count = -1; // naming convention of previous variable didn't match other variables
do // loop terminates at bottom
{
cout << "Enter a person's age or enter 0 to stop\n"; // why \n here instead of endl?
cin >> age;
total += age;
count++;
} while (age > 0); // slightly easier code to write if 0 terminates instead of -1
cout << "Number of people entered:\n" << count << endl;
cout << "Average age of people = " << total / (float)count; // floating point result
}
int main()
{
age();
char temp;
cin >> temp;
}
you should copy the code
cout << "Enter a person's age or enter -1 to stop\n";
cin >> age;
before the while loop.
I am trying to write a program to find the sum of multiple amounts and the average of the amounts given. It doesn't seem to be working but I don't know if the issue is within my compiler of if it is my code. This is what i have so far.
#include <iostream>
using namespace std;
int main()
{
int n, i;
sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
you didn't declare "num" array anywhere, also your data declarations are missing types for sum and average. They should be floats. BTW float literals need f on the end:
float num = 0.0f; // hold the current number
float sum = 0.0f; // store the sum so far
float average = 0.0f; // store the average at the end
When reading store cin straight into num, with no [i] subscript:
cin >> num;
sum += num;
This will fix the main errors. Again, read the error messages carefully, they will always tell you the line number and a message about the type of error, you just need to learn to decipher what the messages mean.
forget about the array for now, as that would need dynamic memory allocation, since the size is inputted by the user, and you should get basic program flow and variables worked out before delving into that.
"unknown symbol" or similar means you used a name, but you never declared what type of thing that was, so you forgot to declare a variable or didn't declare a type for it (just throwing a name out doesn't tell the compiler whether it's meant to be the name of e.g. a variable, a function, a class or whatever. The compiler isn't a mind reader).
So, I have to do a homework problem that entails the following:
During the tax season, every Friday, J&J accounting firm privides assistance to people who prepare their own tax returns. Their charges are as follows.
a. If a person has low income (<=25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.
b. For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.
(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 x 0.40 x (45 / 60) = $21.00.)
Write a program that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount. The program must contain a function that takes as input the hourly rate, the total consulting time, and a value indicating whether the person has low income. The function should return the billing amount. The program may prompt the user to enter the consulting time in minutes.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
const int HOUR = 60;
int minutes = 0;
double intake(payment);
void intake()
{
char income, y('y'), n('n');
cout << "Is the income rate over 25,000? Y - Yes | N - No): ";
cin >> income;
switch(income)
{
case 'n':
case 'N': low_procedure()
break;
case 'y':
case 'y': high_procedure()
break;
default: cout << "Invalid entry. You must indicate low or high income.\n"
break;
}
}
int main()
{
intake();
cout<<"You owe: \n";
cout<< payment <<endl;
}
double low_procedure()
{
const double LOW_DISCOUNT = 0.40;
const int LOW_TIME = 30;
consult = getConsultTime()
rate = getRate()
if consult > LOW_TIME
{
minutes = consult - LOW_TIME
result = rate * LOW_DISCOUNT
payment = calcPay
}
else
cout <<"No additional fees. \n";
return payment;
}
double high_procedure()
{
const double HIGH_DISCOUNT = 0.70;
const int HIGH_TIME = 20;
consult = getConsultTime()
rate = getRate()
if consult > HIGH_TIME
{
minutes = consult - HIGH_TIME
result = rate * HIGH_DISCOUNT
}
else
cout<<"No additional fees.";
}
int getConsultTime()
{
int consult = 0;
cout << "How long was the consult for in minutes? \n";
cin >> consult;
return consult;
}
double getRate()
{
double rate = 0.00;
cout << "What was the hourly rate? \n";
cin >> rate;
return rate;
}
double calcPay
{
double payment = 0.00;
payment = result * (minutes/HOUR);
return payment;
}
I've been having a lot of trouble here since I realized that I need to declare variables in code. I have a feeling I'm making this more complex than it needs to be, but the switch statement is important. I'm trying to sieve through bad, unimportant data.
You should declare them in the smallest scope that makes sense. Since you are apparently using them in multiple functions, the file scope (which is generally thought of as 'globally', not 'locally') seems appropriate.
As an alternative, you could make a class that has the variables and functions as members, but under the circumstances it seems overkill...
One way to do this is to group data into a struct, make a instance of that struct for each person, and make all functions accept a pointer or a reference of that struct and access its fields.
(When you learn classes then you can forget about this answer.)
There are a lot of reasons to avoid global variables (like namespace pollution).
Even if you limit them to file scope or namespace scope, there are still a lot of reasons to avoid variables with static storage duration (like thread safety, initialization order).
The rule of thumb is always "to use the smallest scope possible".
#include <iostream>
using namespace std;
struct AccountData {
int consult;
int minutes;
double rate;
double result;
double payment;
};
AccountData makeAccount(int consult, int minutes, double rate, double result, double payment)
{
return AccountData({consult, minutes, rate, result, payment});
}
void high_procedure(AccountData *thisAccount)
{
cout << "do something with the account, like printing out \"payment \""
<< thisAccount->payment
<< "\n";
}
void low_procedure(AccountData *thisAccount)
{
thisAccount->payment+=1.0;
cout << "do something with the account, like adding 1 to \"payment \""
<< "\n";
}
int main() {
AccountData account1 = makeAccount(1,2,3,4,5);
high_procedure(&account1);
low_procedure(&account1);
high_procedure(&account1);
AccountData account2 = makeAccount(10,20,30,40,50);
high_procedure(&account2);
low_procedure(&account2);
high_procedure(&account2);
return 0;
}
Demo:
https://ideone.com/sWVoHF