I dont understand why i am not getting total.
The question is
Define a class student with the following specification:Private
members of class student admno integer sname 20 character eng.
math, science float total float ctotal() a function to calculate eng +
math + science with float return type. Public member function of
class student Takedata() Function Public member function of class
student Takedata() Function float ctotal() a function to calculate
eng + math + science with floa return type. Public member function
of class student Takedata() Function
#include<stdio.h>
#include<iostream>
using namespace std;
class Student
{
private:
int admno;
char sname[20];
float english,maths,science;
float total;
float ctotal()
{
total=(english+maths+science);
return(total);
}
public:
void Takedata()
{
cout<<"Enter the value of admno:";
cout<<" sname :";
cout<<"eng :";
cout<<"science:";
cout<<"maths:";
cin>>admno;
cin>>sname;
cin>>english;
cin>>science;
cin>>maths;
}
Student(): total(0.0) //constructor
{
}
friend float func(Student);
void Showdata()
{
cout<<"adm no:"<<admno;
cout<<"sname:"<<sname;
cout<<"eng"<<english;
cout<<"science"<<science;
cout<<"maths"<<maths;
}
};
float func(Student t)
{
t.total;
return t.total;
}
int main()
{
Student s1;
s1.Takedata();
s1.Showdata();
cout<"total is:";
cout<<func(s1);
}
Need to make either total or method ctotal() public.
Then call either one of them from
public:
float total;
float func(Student t)
{
t.total;
return t.total;
}
OR
public:
float ctotal() {
total=(english+maths+science);
return(total);
}
float func(Student t)
{
return t.ctotal();
}
func should be defind like this
float func(Student t)
{
return t.ctotal();
}
also edit
cout<"total is:";
to
cout<<"total is:";
Replace t.total with t.ctotal() in
float func(Student t)
{
t.total;
return t.total;
}
Related
Anyone can help me to make function using OOP? How to be able to make the function of finding the average of height of students with OOP?
class Person
{
//data members
private:
string name;
int age;
int height;
float weight;
//member functions
public:
void setPerson(string n, int a, int h, float w)
{
name=n;
age=a;
height=h;
weight=w;
}
void setName(string n) { name=n; }
void setAge(int a) { age=a; }
void setHeight(int h) { height=h; }
void setWeight(int w) { weight=w; }
string getName() {return name;}
int getAge() {return age;}
int getHeight() {return height;}
float getWeight() {return weight;}
};
int main()
{
Person p[100];
int x;
cin >> x;
string name;
int age;
int height;
float weight;
for(int i=0; i<x; i++)
{
cin >> name >> age >> height >> weight;
p[i].setName(name);
p[i].setAge(age);
p[i].setHeight(height);
p[i].setWeight(weight);
}
..............
my input are :
3 (number of person)
jason 20 185 70.50 (name age height weight)
emma 19 165 55.55
yerry 25 164 65.10
output :
171.33
Once you have your Persons recorded, it's just a matter of calculating the average height. It should not be a member function of Person, as the class is intended to represent a single Person. An average height is not a property or action taken on/by/to a single Person, so we just calculate it in main().
I've noted changes that I made to your code.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
class Person {
// data members
private:
std::string name;
int age;
int height;
float weight;
// member functions
public:
// CHANGE: Change function to constructor
Person(std::string n, int a, int h, float w)
: name(n), age(a), height(h), weight(w) {}
void setName(std::string n) { name = n; }
void setAge(int a) { age = a; }
void setHeight(int h) { height = h; }
void setWeight(int w) { weight = w; }
std::string getName() { return name; }
int getAge() { return age; }
int getHeight() { return height; }
float getWeight() { return weight; }
};
int main() {
std::vector<Person> p; // CHANGE: Switch from C-array to std::vector
int x;
std::cin >> x;
std::string name;
int age;
int height;
float weight;
for (int i = 0; i < x; i++) {
std::cin >> name >> age >> height >> weight;
p.emplace_back(name, age, height,
weight); // CHANGE: Take advantage of vector functionality
// to build Person directly into vector
}
// ADDITION: Calculating average height, std::for_each is subjective here,
// this could have easily been a range-based for loop.
double avgHeight = 0.0;
std::for_each(p.begin(), p.end(), [&avgHeight, size = p.size()](auto person) {
avgHeight += static_cast<double>(person.getHeight()) / size;
});
std::cout << std::fixed << std::setprecision(2) << avgHeight << '\n';
}
Output:
171.33
std::for_each may look goofy, but it's literally just summing heights and dividing by the number of Persons. Like I noted, it could also just be a range-based for loop. I prefer the range-based for loop in this case; I only have std::for_each() because it was a quicker change from my failed attempts at coercing std::reduce to work.
double avgHeight = 0.0;
for (auto i : p) {
avgHeight += static_cast<double>(i.getHeight()) / p.size();
}
The type of i would be better specified as const auto&, but your getters are not marked as const.
You could add a parent struct for Person (call it Individual or something) that has a vector pointer as a member variable. For example, std::shared_ptr<std::vector<double> > Students ( new std::vector<double>() ); The struct would have all the public functions that Person has as pure virtual functions.
Then, add a new void function to Person that derefs Students, and pushes back the height of a new student. Next, you add another function (returning a double or float) that loops through Students to take the sum of the students' heights, and divides it by the size() of the vector.
All Person objects will have pointers to a single Students vector, so every time you push back the height of a new student, it will go to the same place.
I'm designing a strategy pattern based on the following diagram:
I have to base the entire program on two things: the contents of the main function, and the Sale function getTotal() - which I was provided with;
Here's what I managed to write so far:
class Product {
private:
int code;
string type;
string description;
int price;
public:
Product(int code, string type, string description, int price): code{code}, type{type}, description{description}, price{price}{}
int getPrice() {
return price;
}
};
class SaleItem {
private:
Product product;
public:
int quantity;
Product getProduct() {
return product;
}
int getQuantity() {
return quantity;
}
};
class Sale {
public:
SaleItem s;
Sale(SaleItem s) : s{ s }{}
vector<SaleItem> items;
void additem(int n, Product p) {
items.push_back(s(n,p));
}
double getTotal();
};
class DiscountPolicy {
public:
virtual double getDiscount(const Sale* s, SaleItem si) = 0;
};
class CreditCardDiscount : public DiscountPolicy {
public:
virtual double getDiscount(const Sale* s, SaleItem si) {
return si.getQuantity() * si.getProduct().getPrice() * 0.02;
}
};
class NoDiscount : public DiscountPolicy {
public:
virtual double getDiscount(const Sale* s, SaleItem si) {
return si.getQuantity() * si.getProduct().getPrice() * 0.00;
}
};
double Sale::getTotal() {
double total = 0;
for (int i = 0; i < items.size(); i++) {
SaleItem sIt = items[i];
double price = sIt.getQuantity() * sIt.getProduct().getPrice();
//apply discount
price -= discountPolicy->getDiscount(this, sIt);
total += price;
}
return total;
}
int main() {
Sale s(new NoDiscount());
Product p1(1, "Apple", "food", 2.0);
Product p2(1, "TV", "electronics", 2000.0);
s.addItem(3, p1);
s.addItem(1, p2);
assert(s.getTotal() == 2006);
Sale s2(new CreditCardDiscount());
s2.addItem(3, p1);
s2.addItem(1, p2);
//total with discount for card
assert(s2.getTotal() == 1965.88);
}
I'm currently encountering two issues:
I can't wrap my head around designing the Sale class so that "Sale s(new NoDiscount());" and " Sale s2(new CreditCardDiscount());", from the main class, make sense.
I'm fairly certain there should be some code where the //apply discount comment is found in the getTotal() function, but I'm not sure how to implement it so that "price -= discountPolicy->getDiscount(this, sIt);" works.
The rest of the program should be implemented correctly, since I've seen similar designs, it's mainly the Sale function that I don't understand.
Appreciate the help!
I am doing this code for my OOP lab and i am getting the following problem, i have tried many things but all in vain:
#include<iostream>
using namespace std;
void ad(&mt &ft){
mt.m=mt.m+(mt.c/100);
ft.f=ft.f+(ft.i/12);
if(t==0){
m=mt.m+(ft.f/3.281);
m=round(m);
c=(int)(m%100);
m=(int)(m/100);
}
else if(t==1){
f=ft.f+(mt.m*3.281);
f=round(f);
i=(int)(f%12);
f=(int)(f/12);
}
}
class dm{
private:
float m,c;
int t=0;
public:
void get(){
cout<<"\nEnter the distance in metres and centimeteres:\t";
cin>>m>>c;
}
void display(){
cout<<"\nThe distance stored is:\t"<<m<<" meters "<<c<<" centimeters.";
}
friend void ad(dm db);
};
class db{
private:
float f,i;
int t=1;
public:
void get(){
cout<<"\nEnter the distance in feet and inches:\t";
cin>>f>>i;
}
void display(){
cout<<"\nThe distance stored is:\t"<<i<<" feet "<<f<<" inches.";
}
friend void ad(dm db);
};
float round(float var){
float value = (int)(var * 100 + .5);
return (float)value / 100;
}
int main(){
dm dm1, dm2;
db db1, db2;
dm1.get();
db1.get();
dm2.add(dm1 db1);
db2.add(dm1 db1);
dm2.display();
db2.display();
return 0;
}
I am getting the following Errors:
variable or field 'ad' declared void
'mt' was not declared in this scope
'ft' was not declared in this scope
please help, Thanks in advance
Your complete program is full of syntax and logical errors. First read how an object is passed and what is the scope of a variable in c++. You will then understand the mistakes you have done.
I re-wrote the code like:
#include<iostream>
using namespace std;
class db;
class dm{
float mt,cm;
public:
void getdata()
{
cout<<"CLASS DM: \n\n";
cout<<"Enter Values for metres : ";
cin>>mt;
cout<<"Enter Values for centimetres: ";
cin>>cm;
}
void display()
{
cout<<"\nTotal value of distance is : "<<mt<<" meters "<<cm<<" centimeters.";
}
friend dm add(dm, db);
friend db add(db, dm);
};
class db{
float ft,in;
public:
void getdata()
{
cout<<"CLASS DB: \n\n";
cout<<"Enter Values for feet : ";
cin>>ft;
cout<<"Enter Values for inches: ";
cin>>in;
}
void display()
{
cout<<"\nTotal value of distance is : "<<ft<<" feet "<<in<<" inches.";
}
friend dm add(dm, db);
friend db add(db, dm);
};
dm add(dm a, db b){
dm temp;
temp.cm=a.cm + (a.mt*100) + (b.ft*30.48) + (b.in*2.54);
temp.mt=(int)(temp.cm/100);
temp.cm=(int)(temp.cm-(temp.mt*100));
return (temp);
}
db add (db b, dm a){
db temp;
temp.in=b.in + (b.ft*12) + (a.mt*39.37) + (a.cm*2.54);
temp.ft=(int)(temp.in/12);
temp.in=(int)(temp.in-(temp.ft*12));
return (temp);
}
int main(){
dm dm1, dm2;
db db1, db2;
db1.getdata();
dm1.getdata();
dm2=add(dm1, db1);
db2=add(db1, dm1);
dm2.display();
db2.display();
return 0;
}
The errors are resolved and it is working fine now, Thank you everyone for their help
I want float variable 'avg' to be returned and then in the main pass it to 'void batsman::display(float a)' using a parameter. then display the average marks in display method. this method gives me 2 errors. any other way?
#include<iostream.h>
class batsman
{
int marks[5];
char name[15],country[15];
public:
void input();
float cal();
void display();
};
void batsman::input()
{
int i;
cout<<"Enter player name: ";
cin>>name;
cout<<"Enter player country: ";
cin>>country;
cout<<"Enter player marks"<<"\n";
for(i=0;i<5;i++)
{
cout<<"Mark "<<i+1<<": ";
cin>>marks[i];
}
}
float batsman::cal()
{
int i;
int tot=0;
float avg;
for(i=0;i<5;i++)
{
tot=tot+marks[i];
}
avg=(float)tot/5;
return avg;
}
void batsman::display(float a)
{
float avg1;
avg1=a;
cout<<"Player name: "<<name<<"\n";
cout<<"Player country: "<<country<<"\n";
cout<<"Average: "<<avg1<<"\n";
}
int main()
{
batsman b1;
b1.input();
b1.cal();
b1.display(b1.batsman::cal());
//cout<<"Average: "<<b1.batsman::cal()<<"\n";
}
The code has several errors.
iostream.h should be iostream
using namespace std; // add this at top so that cout is found
display() should be display(float a) in the class declaration.
After those changes the code ran as expected.
Change display's definition in your class to display(float a), and prepend std:: to cout and cin. As a recommendation, don't use iostream.h, use iostream.
I don't know how to call my class functions into printData(Testscore&) and readData(TestScore).
Also, could someone tell me why my Average() isn't being called to the main? I just learned about using static member variables and static member functions and was wondering if I am using them incorrectly.
The readData function:
Does not use copy constructor.
Reads all instance variables like the student's names and all their
grades.
Uses functions to store the variables, name, element of each grade of array pointed to private pquiz, and static member
grades of how many grades to read.
The printData function:
Writes the name and average grade of the quizzes.
Uses copy constructor.
This is my program so far:
#include <iostream>
#include <string>
using namespace std;
class TestScore {
private:
static int grades;
string name;
double *pquiz;
double average;
public:
TestScore();
~TestScore();
void setName(string);
static void setGrades(int);
void setPquiz(double *);
void setAverage(double);
string getName();
static int getGrades();
double getPquiz();
void readData(TestScore &);
void printData(TestScore);
double Average(double *, int);
static void Grade(int);
};
TestScore::TestScore() {
name="";
pquiz=new double[grades];
average=0;
}
void TestScore::setName(string name1) {
if(name1!="1") {
name=name1;
}
}
void TestScore::setPquiz(double *pquiz1) {
if(pquiz>=0) {
pquiz=pquiz1;
}
}
void TestScore::setGrades(int grades1) {
if(grades1>=0) {
grades=grades1;
}
}
void TestScore::setAverage(double average1) {
if(average1>=0) {
average=average1;
}
}
string TestScore::getName() {
return name;
}
int TestScore::getGrades() {
return grades;
}
double TestScore::getPquiz() {
return *pquiz;
}
double Average(double *pquiz, int grade) {
int count;
double total=0;
double average=0;
for(count=0; count<grade; count++) {
total+=pquiz[count];
}
average=total/grade;
return average;
}
void readData(TestScore&) {
}
void printData(TestScore) {
}
TestScore::~TestScore() {
delete [] pquiz;
pquiz=0;
}
int TestScore::grades=0;
void TestScore::Grade(int a) {
grades+=a;
}
int main() {
const int grades = 3;
const int students = 4;
TestScore exam;
string student;
int grade;
double *pquiz;
double average;
for(int i=0; i<students; i++) {
cout<<"Student "<<(i+1)<<": ";
cin>>student;
exam.setName(student);
cout<<endl;
for(int count=0; count<grades; count++) {
cout<<"Quiz "<<(count+1)<<": ";
cin>>pquiz[count];
exam.setPquiz(pquiz);
exam.getPquiz();
while(pquiz[count]<0) {
cout<<"Error, invalid test score, please try again."<<endl;
cout<<"Quiz "<<(count+1)<<": ";
cin>>pquiz[count];
}
}
exam.setAverage(average);
cout<<exam.getName()<<" average is "<<Average(pquiz, grade)<<endl<<endl;
}
readData(exam);
printData(exam);
return 0;
}
Don't use static anywhere, at least not for now. You have too many variables of the same name, scattered all over the place. Try to clean them up.
TestScore::TestScore()
{
name = "";
//pquiz = new double[grades];//#grades is undefined
pquiz = NULL;
average = 0;
}
grades is not defined yet, it could be zero, or it could be -817. You should just remove that line, or you can put something like pquiz = new double[10] that's if you are sure the number of quiz will not exceed 10.
TestScore::~TestScore()
{
if (pquiz) delete[] pquiz;
pquiz = NULL;
}
delete pquiz only if it is not NULL
int main() {
const int grades = 3;
const int students = 4;
TestScore exam;
string student;
int grade;
double *pquiz;
...
This is a different pquiz, it is a pointer which points to nothing, it doesn't really exist, you can't use it like that.