This code simply takes a number, adds this to another number and then prints the result out. It also says whether the number is high or low. This is all done in a bool function:
#include <iostream>
using namespace std;
bool addition(int num, int num2, int total);
int main()
{
int num, num2,total;
cout << "enter a number"<< endl;
cin >> num;
cout<< "enter another number" << endl;
cin >> num2;
addition(num, num2, total);
{
cout <<"the first number is:" << num<< " the second number is: "<< num2 << endl;
cout << "the total is: " << total << endl;
if (1) {
cout << "its low" ;
} else {
cout << "its high";
}
cout << endl;
}
}
bool addition (int num, int num2, int total) {
//total = 0;
total = num + num2;
if (total >= 10){
return 1;
} else {
return -1;
}
}
The problem is this program is ALWAYS saying the number is low and the total is ALWAYS 32767. I don't know why.
You're passing total by value, which means addition() can't modify main's total variable. Pass by reference instead:
bool addition (int num, int num2, int &total)
The reason you always get "its low" is because if (1) is always true. Probably you want something like:
bool result = addition(num, num2, total);
Followed later by:
if (result)
You are passing total by its value. Use pointer or reference instead to modify its value inside the addition function.
Besides, returning 1 or -1 from a function with a boolean return type has same effect, as in C++ any nonzero value evaluates to true. Return either true or false (or either some nonzero value or 0).
Try passing total by reference instead of value like this:
bool addition (int num, int num2, int &total)
instead of
bool addition(int num, int num2, int total);
Also your condition if (1) is always true. So you will always get low
#include <iostream>
using namespace std;
bool addition (int num, int num2, int &total) {
total = num + num2;
return total >= 10;
}
int main()
{
int num, num2,total;
cout << "enter a number"<< endl;
cin >> num;
cout<< "enter another number" << endl;
cin >> num2;
bool additionResult = addition(num, num2, total);
{
cout <<"the first number is:" << num<< " the second number is: "<< num2 << endl;
cout << "the total is: " << total << endl;
if (!additionResult){
cout << "its low" ;
}
else{
cout << "its high";
}
cout << endl;
}
}
Related
Trying to fulfill the coding prompt
Input a list of positive numbers, find the mean (average) of the numbers, and output the result. Use a subprogram to input the numbers, a function to find the mean, and a subprogram to output the result.
I have done smaller calls with passing arguments but this one requires 3 separate subprograms, 1 for input, 1 for calculations and one to display the result.
So far my program is does not start the initial call for input
#include <iostream>
using namespace std;
//prototypes
int prompt(int sum, int count );
float average(int sum, int count);
void result(float avg);
int main()
{
int num;
cout << "Welcome to Keith's Averaging program";
cout << endl;
int prompt();
int average (int sum, int count);
void result (float avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt()
{
int num, sum, count;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
Displays my welcome message then exits
I have put some comments in your code as explanation.
#include <iostream>
using namespace std;
//prototypes // These are declarations, definitions should also contain
// same function signatures
int prompt(int& sum, int& count); // accept arguments as reference (Read about it)
float average(int& sum, int& count);
void result(float& avg);
int main()
{
// int num; // don't need num in this function, not used
int sum = 0, count = 0; // create variables sum and count and initialize them to 0
float avg;
cout << "Welcome to Keith's Averaging program";
cout << endl;
prompt(sum, count); // don't need function return type and argument return type when calling
// a function
cout << sum << " " << count << endl; // print the values after prompt() call
// prompt() call must have filled the values sum and count
average(sum, count);
result(avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt(int& sum, int& count)
{
int num;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
}
float average(int& sum, int& count){
// TODO: implement this
}
void result(float& avg) {
// TODO: implement this
}
I have changed various parts of your code. I changed the function prototypes so that they take arguments by reference.
In the int main() function, I created two variables sum and count and initialized them to 0 - we will use these variables when calling those functions.
In the int prompt() function, I changed the function signature so that it matches the declared definition (otherwise it would have been some other function). Also, I removed the local declarations sum and count since we now have them as function arguments.
I have also put the definition blocks for other two functions and you can implement them (I have marked them as // TODO).
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.
Basically what I am trying to do is get the lowest number, but the program is feeding me back garbage, but I use the same line of code to get the highest value, only change I made was > to <, the program gives me back the highest value no problem put not the lowest. And I have tried everything I can think of from making the lowest= x[0], lowest=101( user is suppose to enter in grades on scale of 0-100, thought made it had something to do with the value. ) and lowest =highest and it still give me back a number like -9.255596e...., any help or suggestion or greatly appreciated, or maybe a point in the right direction just really trying to understand why it works for one set of numbers and not the others.
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
double average(double,int);
double sum1(double[],int);
double highest(double[], int);
double lowest(double[], int);
int _tmain(int argc, _TCHAR* argv[])
{
double gradeBook[1000];
char x;
int count = 0;
cout << "Do you wish to start the program if so enter y to stop enter q" << endl;
cin >> x;
while (x != 'q')
{
cout << "Enter in test grade on a scale of 0 to 100" << endl;
cin >> gradeBook[count];
if (gradeBook[count]<0 || gradeBook[count]>100)
{
cout << " Please try again ";
count--;
}
else
cout << "valid answer" << endl;
count++;
cout << "Do you wish to continue entering in grades? If so enter y to stop enter q" << endl;
cin >> x;
}
highest(gradeBook, count);
cout << "The highest grade enter is " << highest(gradeBook, count) << endl;
lowest(gradeBook, count);
cout << "The lowest grade enter is " << lowest(gradeBook, count) << endl;
cout << lowest <<endl;
return 0;
}
double highest(double x[], int y)
{
double highest = 0;
for (int i = 0; i<= y; i++)
{
if (x[i]>highest)
highest = x[i];
}
return highest;
}
double lowest(double x[], int y)
{
double lowest = 100;
for (int i = 0; i<= y; i++)
{
if (x[i]< lowest)
lowest = x[i];
}
return lowest;
}
A way to resolve your question is to use code already tested.
In your case you can use min_element and max_element to find min and max element of your code:
cout << "The highest grade enter is " << *max_element(gradeBook,
gradeBook+count) << endl;
I've been trying to write a C++ program that calculates your end of year grade (an exercise given by the Google for Education C++ course). The program works, except for the fact that it doesn't calculate your final grade, instead, it just outputs "0". I have searched the code and can't seem to find the problem.
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(The reason I have a different program for every grade type is because the course states that you should make as many functions as possible)
Either you should pass value to check() as reference or make check to return input value.
Change
int check(int a)
to
int check(int& a)
Second method
Modify check to
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
And use return value to assign input to variables. Like
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
Your cin >> a statements updates value of a local variable which is gone as soon as check() returns. You want to update value of variables that are actually used for calculating grades. Just change the function check() to pass by reference check(int &a) or pass a pointer check(int *a)
I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);