I was experimenting with classes and I wrote this example code. The user enters their register number and two marks. The output should be their register number and the average of the two input marks. I have two questions:
How do I use the float type to display the output average marks in decimal form if I am using constructors?
Why is the output of the register number not correct? The code is given below.
#include<iostream.h>
#include<conio.h>
class abc
{
int reg, mark1, mark2;
public:
int avg;
abc(int reg, int mark1, int mark2)
{
avg = (mark1 + mark2) / 2;
}
void display()
{
cout<<"Your average mark is:\n"<<avg<<"\n";
cout<<"Your Register Number is:\n"<<reg<<"\n";
}
};
void main()
{
clrscr();
int num, m1, m2;
cout << "Enter your register number\n";
cin >> num;
cout << "Enter your Mark 1 and Mark 2:\n";
cin >> m1 >> m2;
abc s1(num,m1,m2);
s1.display();
getch();
}
I am getting the average (without the decimal) and the register number output is 11196.
In C++ the constructor arguments are not automatically stored in the class members. I would change your class declaration to the following, note that I have used different names for the members and function arguments (I like to use m_ for private member variables).
class abc
{
int m_reg, m_mark1, m_mark2;
public:
int avg;
abc (int reg, int mark1, int mark2)
: m_reg(reg), m_mark1(mark1), m_mark2(mark2)
{
avg = (m_mark1+m_mark2)/2;
}
void display()
{
cout<<"Your average mark is:\n"<<avg<<"\n";
cout<<"Your Register Number is:\n"<<m_reg<<"\n";
}
};
If you expect your result to be a decimal (and not rounded or floored to the nearest integer) you need to change your average declaration and calculation to:
// The new declaration
double avg;
// In your constructor
avg = (double) (m_mark1 + m_mark2) / 2.0;
All you need to do is add value to reg property in your class constructor:
abc (int r, int mark1, int mark2)
{
reg = r;
avg = (mark1+mark2)/2;
}
In addition to that, why is avg an integer instead of double? Consider this:
class abc
{
int reg,mark1,mark2;
public:
double avg;
abc (int r, int mark1, int mark2)
{
reg = r;
avg = (double)(mark1+mark2)/2.00;
}
void display()
{
cout<<"Your average mark is:\n"<<(int)avg<<"\n";
cout<<"Your Register Number is:\n"<<reg<<"\n";
}
};
If you want 4.4 to be displayed as 4, and 4.5 as 5 use this hack:
avg = avg + 0.5;
cout << (int)avg << "\n";
Related
I need to create a program that accepts 3 numbers and find the sum, average and product. I only need to use main(), get_ABC(), compute() and display() functions. I did it right but im not getting the right output about my mathematical operations.
#include<conio.h>
#include<iostream.h>
float get_A(float A)
{
cout<<"Enter First Number: ";
cin>>A;
return(A);
}
float get_B(float B)
{
cout<<"Enter Second Number: ";
cin>>B;
return(B);
}
float get_C(float C)
{
cout<<"Enter Third Number: ";
cin>>C;
return(C);
}
float compute_sum(float A,float B,float C)
{
float sum;
sum = A + B + C;
return(sum);
}
float compute_ave(float A,float B,float C)
{
float ave;
ave = (A + B + C) / 3;
return (ave);
}
float compute_prod(float A,float B,float C)
{
float prod;
prod = A * B * C;
return(prod);
}
void display(float sum,float ave,float prod)
{
cout<<"The sum of three numbers is "<<sum<<".\n";
cout<<"The average of three numbers is "<<ave<<".\n";
cout<<"The product of three numbers is "<<prod<<".";
}
float main()
{
float A,B,C;
float sum;
float ave;
float pro;
clrscr();
get_A(A);
get_B(B);
get_C(C);
sum = compute_sum(A,B,C);
ave = compute_ave(A,B,C);
pro = compute_prod(A,B,C);
display(sum,ave,pro);
getch();
return(0);
}
This is the output.
Enter First Number: 1
Enter Second Number: 2
Enter Third Number: 3
The sum of three numbers is 0.
The average of three numbers is 0.
The product of three numbers is 0.
I really need help. My prof give me this problem without teaching how to code, so i only come up with basics, i really gave up and end up here. You can change, add or replace the codes(with basic codes) if you want and i'll appreciate it.
Change this:
get_A(A);
get_B(B);
get_C(C);
to this:
A = get_A(A);
B = get_B(B);
C = get_C(C);
so that you use the return values of your functions.
Moreover, main() should return an int, not a float.
Furthermore, initialize your variables when you declare them, so that you avoid "is used uninitialized in this function" warnings.
I keep getting the error "error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] " and I do not know why;
I am doing this for homework and we have yet to discuss pointers so using them is out of the question.
here is my code (PS I am new to programming)
#include <iostream>
#include <cmath>
using namespace std;
double normalize (int , int);
double normalize (double,double);
int n=0;
int i=0;
const double SIZE=5;
double mean=0;
double meanDivide;
int main()
{
char dataType;
int norm[5];
int value =1;
cout<<"Which data type do you want (i, d): ";
cin>>dataType;
if (dataType =='i')
{
while(value<5)
{
cout<<"Enter value "<<value << ": ";
cin>> norm[n];
value++;
}
}
else if (dataType=='d')
{
cout<<"Enter value "<<value << ": ";
cin>> norm[n];
value++;
}
cout<<"The mean is: "<<normalize(norm,5)/* The error comes from here and
I do not know what to do or why */
<<endl;
cout<<"The normalized values: "<<endl;
int j=0;
cout<<"norm[1] = "<<norm[j]<<endl;
j++;
cout<<"norm[2] = "<<norm[j]<<endl;
j++;
cout<<"norm[3] = "<<norm[j]<<endl;
j++;
cout<<"norm[4] = "<<norm[j]<<endl;
j++;
cout<<"norm[5] = "<<norm[j]<<endl;
return 0;
}
double normalize(int norm[],int SIZE)
{
while(i<6)
{
meanDivide +=norm[i];
i++;
}
i=0;
while (i<n)
{
norm[i] -=meanDivide;
i++;
}
mean = meanDivide / 5;
return mean;
}
double normalize (double norm[],double SIZE)
{
while(i<6)
{
meanDivide +=norm[i];
i++;
}
i=0;
while (i<n)
{
norm[i] -=meanDivide;
i++;
}
mean = meanDivide / 5;
return mean;
}
This is the output I should be getting.
//For integers:
Which data type do you want (i, d): i
Enter value 1: 0
Enter value 2: 3
Enter value 3: 4
Enter value 4: 8
Enter value 5: 12
The mean is: 5.4
The normalized values:
norm[1] = -5
norm[2] = -2
norm[3] = -1
norm[4] = 2
norm[5] = 6
//For doubles:
Which data type do you want (i, d): d
Enter value 1: 5.5
Enter value 2: 1.23
Enter value 3: 2.02
Enter value 4: 9.99
Enter value 5: 6.32
The mean is: 5.012
The normalized values:
norm[1] = 0.488
norm[2] = -3.782
norm[3] = -2.992
norm[4] = 4.978
norm[5] = 1.308
You are declaring your methods like this :
double normalize (int , int);
double normalize(double*, double);
Yet you are trying to implement them like :
double normalize(int norm[], int SIZE) {/*...*/}
double normalize(double norm[], double SIZE) {/*...*/}
Notice that the argument types are not the same, int, int is not the same as int[], int. This means that your implementation is actually defining a whole new function, unrelated to the ones you declared at the top of your example. When you call your normalize function, only the initial declaration is found, and it tries to match int norm[5] to int which it fails. To fix this, make sure the declaration is correct. Change the declarations to this :
double normalize(int[], int);
double normalize(double[], double);
This will fix the error you are asking about in this question, but your example still has other problems. Some of them are identified in the comments.
You declare prototypes for non-pointer parameters:
double normalize (int , int);
double normalize (double,double);
You call with pointer arguments:
cout<<"The mean is: "<<normalize(norm,5)
The C++ compiler at that point does not care about the implementation with pointer arguments below. Try matching implementation to prototypes.
Also
a) you increment value but use n as index:
cin>> norm[n];
value++;
b) you ignore SIZE
c) SIZE should be unsigned int in both cases
d) your example is not minimal (https://stackoverflow.com/help/mcve)
You might find this generally useful:
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
#include <iostream>
using namespace std;
int g_c_d(int n, int d);
class Fraction
{
private:
//variables to store numerator and denominator
int num;
int denom;
public:
Fraction(){}
Fraction(int num): num(num) {}
Fraction(int num, int denom): num(num), denom(denom) {}
void set_num(int n){ num = n;}
void set_denom(int d){ denom = d;}
int get_numerator() const {return num;}
int get_denominator() const {return denom;}
};
int g_c_d(int n, int d){
return d == 0? n : g_c_d(d, n % d);
}
istream &operator>> (istream &input, Fraction &f)
{
int n, d;
char slash;
input >> n;
input >> slash;
input >> d;
if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
f = Fraction(n, d);
return input;
}
ostream &operator<<(ostream &output, const Fraction &frac)
{
return output << frac.get_numerator() << "/" << frac.get_denominator();
}
int main()
{
int n, d;
Fraction frac;
int gcd;
n = frac.get_numerator();
d = frac.get_denominator();
gcd = g_c_d(frac.get_numerator() , frac.get_denominator());
cout << "Enter a fraction" << endl;
cin >> frac;
frac.set_num(n/gcd);
frac.set_denom(d/gcd);
cout << "your fraction is: ";
cout << frac << endl;
return 0;
}
Hi im trying to simplify fractions entered by a user. However everytime I enter a fraction that is to be simplified the output returned is "1/0".
Can some one please help, it'll be massively appreciated!
The problem is that you do all your computations on frac before asking the user to input a fraction — and then you overwrite whatever the user inputs. You need to move this bit:
cout << "Enter a fraction" << endl;
cin >> frac;
much, much higher up.
When you are setting up the code you have:
Fraction frac;
This calls the default constructor for Fraction. Because you never initialized the members in the constructor you get the default initizliation for the int type which is 0. Then:
n = frac.get_numerator();
d = frac.get_denominator();
This makes n and d 0. From that point onwards you are using those values of n and d. These values however are not the values from the user inputted frac but are just the values you get from the defaults. Change your code to read in the user inputted value for frac before you do any calculations.
The main lesson to learn here is to make sure you don't use uninitialized variables. Generally speaking when you compile with all warnings enabled this is the sort of thing that compilers will warn about.
You may be diving by zero because the default constructor doesn't assign value to the denominator. In the case where the denominator is set to zero, the gcd() function will divide by zero, on the first time in main.
I am working on some programming homework and I am trying to use a for-loop in order to facilitate the process of the coding. Here is the loop:
#ifndef DIVSALES_H
#define DIVSALES_H
class DivSales
{
public:
DivSales(){ quarterSales[4] = {0}; };
double getTotalSales() { return totalSales;}
static void setTotalSales(double);
static void addTotalSales(double);
double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
private:
static double totalSales;
double quarterSales[];
};
double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H
#include <iostream>
#include "DivSales.h"
using namespace std;
int main()
{
const int NUMDIVS = 6;
const int NUMQUARTERS = 4;
double amount = 0;
DivSales divs[NUMDIVS];
for(int division = 0; division < NUMDIVS; division++)
{
cout << "Division " << (division + 1) << endl;
for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
{
cout << "Quarter " << (quarter + 1) << ": ";
cin >> amount;
divs[division].setQuarterSales(quarter, amount);
DivSales::addTotalSales(amount);
}
}
return 0;
}
Example of the output:
Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2:
What I am trying to do is make it so that when I have input the numbers for the 4 quarters of a division, that it will move onto the next division. However, after 4 inputs it is not incrementing the division variable of the for-loop instead it continues asking for more inputs. What is going on?
I have found what's causing that problem, it is in the file DivSales.h:
Change this line:
double quarterSales[];
For this line:
double quarterSales[4];
The problem was that you were not allocating memory for an array of 4 elements. To initialize it, change your constructor to this:
DivSales():quarterSales({0}){ };
You should also move the following line to DivSales.cpp, because otherwise I was getting a multiple definition error:
double DivSales::totalSales = 0;
Here:
divs[division].setTotalSales(amount);
you probably want:
divs[division].addTotalSales(amount);
But that is not what is causing your problem. Which I cannot reproduce.
I am some-what new to Programming in c++ i was assigned a exercise what i'm getting a compile error
i was hoping someone can either help me resolve the error or give me some insight as to why its happening
Code below
/*
Exercise 21 Intermediate: Declare a seven-row, two- column int array named temperatures.
The program should prompt the user to enter the highest and lowest temperatures for seven days.
Store the highest temperatures in the first column in the array.
Store the lowest temperatures in the second column.
The program should display the average high temperature and the average low temperature.
Display the average temperatures with one decimal place.
*/
#include <iostream>
#include <iomanip>
using namespace std;
//function prototype
void calcAverage(double temperatures[7][2]);
main()
{
double temperatures[7][2] = {0};
float high = 0.0;
float low = 0.0;
double high_average = 0.0;
double low_average = 0.0;
cout << "Please enter the high then low for the last 7 days " <<endl;
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the High for day: "<< x+1<<": ";
cin >> high;
temperatures[0][x] = high;
}
for(int x = 0; x < 6; x += 1)
{
cout << "Please enter the Low for day: "<< x+1<<": ";
cin >> low;
temperatures[1][x] = high;
}
//Error is here
calcAverage(high_average, low_average);
// end error
system("pause");
}
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
{
float accumulator = 0.0;
//for hot average
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[0][x];
}
high_average = accumulator;
// for cold average
accumulator = 0.0;
for(int x = 0; x < 6; x += 1)
{
accumulator += temperatures[1][x];
}
low_average = accumulator;
}
44 cannot convert double' todouble ()[2]' for argument 1' tovoid calcAverage(double ()[2])'
void calcAverage(double temperatures[7][2]);
Okay, calcAverage takes a two-dimensional array of doubles.
calcAverage(high_average, low_average);
But you passed it two doubles.
void calcAverage(double temperatures[6][1],double &high_average, double &low_average)
And now it takes a two-dimensional array of doubles and two references.
Pick one of these three and stick to it.