Asking for numbers using classes - c++

The program should be like this:
1-ask for series and then parallel resistance (different classes)
2-pass Eq_R_Series and Eq_R_Paralel values(after they are calculated) to the Equivalent resistance that will calculate the Eq_R_Total
3-Display the Eq_R_Total.
so i need the main function and 3 classes(1 of the classes needs the info from the other 2).
class Serie
{
private:
int i, n = 4;
float R_Eq_S;
float r[4];
public:
float serie()
{
for (int i = 0; i < n; i++)
{
cout << "Resistence " << i + 1 << " ";
cin >> r[i];
R_Eq_S = R_Eq_S + r[i];
}
return R_Eq_S;
}
};
int main()
{
Serie s;
s.serie();
}
So i have the program with no errors now (doesn't mean theres nothing wrong), it runs and asks me to introduce the 1st resistence but after that it doesn't continue the cycle.
(i "just" need help to "link" the class to the main and the principal class.)
so this is my basic approach and it works but this is very limited, with a for i can change the number of resistance with one simple editing.
Thanks guys for the help even if it was just to point my mistakes ;) at least i think i'm learning
class Series
{
private:
float R1, R2, R3, R4;
public:
float R_Eq_S;
float series()
{
cout << "Resistance1= ";
cin >> R1;
cout << "Resistance2= ";
cin >> R2;
cout << "Resistance3= ";
cin >> R3;
cout << "Resistance4= ";
cin >> R4;
R_Eq_S = R1 + R2 + R3 + R4;
return R_Eq_S;
}
};
class Parallel{
private:
float R5, R6;
public:
float R_Eq_P;
float parallel(){
cout << "\nResistance5= ";
cin >> R5;
cout << "Resistance6= ";
cin >> R6;
R_Eq_P = (R5*R6) / (R5 + R6);
return R_Eq_P;
}
};
class Equivalent{
private:
float R_Eq;
public:
float r_eq()
{
Series s;
Parallel p;
R_Eq = s.series()+ p.parallel();
return R_Eq;
}
};
int main()
{
Equivalent r;
cout<<"\n\nR_Eq= "<<r.r_eq()<<endl;
}

#Tyler has pointed it in his comment. In your class definition r is declared as of type int. Then, in the expression r[i], i should be a pointer (this is usual C/C++ symmetry: a[i] is the same as *(a + i) so one of them should be dereferenceable, the other one being a number, but it does not matter much which one which). Your i is again an int nevertheless.
Second, I don't quite get how can your code compile, serie is a private method yet you call it outside of class's context.

Related

C++ Char array not working

I'm trying to get this program working, but get odd output. I know a char buffer is not ideal here, but it's for an assignment and not of my own design. Here's my code:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
//Place your class definition here
class student {
public:
void inputData(int a, char s[20], float e, float m, float sci);
void printData();
private:
int admno;
char sname[20];
float eng;
float math;
float science;
float total;
float ctotal();
};
int main () //This is your main driver. Do NOT make any changes to it
{
student obj ;
int a;
char s[20];
float e, m, sci;
cin >> a;
cin.getline(s,20);
cin.clear();
cin.ignore(10,'\n');
cin >> e;
cin >> m;
cin >> sci;
obj.inputData(a, s, e, m, sci);
obj.printData();
return 0;
}
//Place your class member function definitions here
void student::inputData(int a, char s[], float e, float m, float sci) {
admno = a;
*sname = *s;
eng = e;
math = m;
science = sci;
total = ctotal();
}
void student::printData() {
cout << "Admission number: " << admno << endl << "Student name: ";
for (int i = 0; i < 20; i++)
cout << sname[i];
cout << endl << "English: " << eng << endl << "Math: " << science << endl << "Science: " << science << endl << "Total: " << total;
}
float student::ctotal() {
return (eng + math + science);
}
Here's my input:
98745
Kyle Smith
98
78
62
Here's the expected output:
Admission number: 98745
Student name: Kyle Smith
English: 98
Math: 78
Science: 62
Total: 238
Here's the actual output:
Admission number: 98745
Student name:  m ╩`uÄM■Å■   ║k`u
English: 98
Math: 62
Science: 62
Total: 238
Please give advice on how to fix. I have to stick with that char buffer, but don't know why I'm getting this corruption.
Thanks!
*sname = *s;
This copies one character, not the entire string. If you want to copy the entire string, you need to use std::strcpy
std::strcpy(sname, s);
or a loop
char* src = s;
char* dst = sname;
while (src) {
*dst = *src;
++src;
++dst;
}
Of course, you could do away with all of this manual string handling and use std::string instead:
//Place your class definition here
class student {
public:
void inputData(int a, std::string s, float e, float m, float sci);
void printData();
private:
int admno;
std::string sname;
float eng;
float math;
float science;
float total;
float ctotal();
};
void student::inputData(int a, std::string s, float e, float m, float sci) {
admno = a;
sname = std::move(s);
eng = e;
math = m;
science = sci;
total = ctotal();
}
Here is what happening:
cin >> a;
cin.getline(s,20);
cin.clear(); // never mind this, doesn't do anything in this context
cin.ignore(10,'\n');
Your int is read and stored in a
cin now contains \n left over after you pressed Enter
getline immediately attempts to read it into s but it discards it, s is now empty, but getline operation is complete.
Why does it still wait for the input of the name? Because cin.ignore is waiting for \n or at least 10 chars to be entered, but the stream buffer is now empty.
You enter your name and press Enter, ignore at least gets its \n and is now complete but your entered string is not stored anywhere. It is just ignored. If it wasn't ignored you would have gotten the 1st char of this string in the output, but you haven't.
Long story short, your input is broken. You should clear that \n after you entered the first number before getline. Only then, after you have your name stored in s you can attempt to pass it to the function, there is no point in passing a pointer to empty array and expecting it to work.

Getting strange value

I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();

The program does'nt give output

I am using the following code to print out the code, and i doesn't show the correct area of the circle. it shows -215487854145 as the area of the circle..
please help me
the code below code:
kindly help me as i am new to this language, i think i did everything right please
#include <iostream>
using namespace std;
int main()
{
int a, r;
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
Two issues.
You are computing a using an unitialised value of r. The program behaviour is undefined. Move it after the cin >> r; statement.
Working in int could cause you issues with overflow. The largest possible value of an int in C++ can be as small as 32767. Use a double instead, and an improved value of PI. Note that the type of 3.14 * r * r is a double anyway, and you're currently forcing a conversion to int.
As for PI itself, it is not included in the C++ standard library. Consider
constexpr double pi = 3.14159265358979323846264338328;
or take one from a mathematics library if you're using one.
You used r in a calculation before you ever read in the value. Move it after you read it in.
cin >> r;
a = 3.14 * r * r ;
Unlike in mathematics,
a = 3.14 * r * r ;
does not define a relationship between a and r (it's not an equation).
Instead, it means "replace the current value of a with 3.14 times the square of the current value of r".
Since you haven't given r a value yet, the result is undefined.
You need to move the lines around a bit in order to not use values that don't exist yet.
You should also not use integers for this, but floating-point.
double r;
cout << "enter Radius";
cin >> r;
double a = 3.14 * r * r ;
cout << "area of circle is " << a;
#include <iostream>
using namespace std;
int main()
{
int a, r;
// your r was not initialized when you use it.
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
right answer:
#include <iostream>
using namespace std;
int main()
{
int a, r;
cout << "enter Radius";
cin >> r;
//after r being initialized.
a = 3.14 * r * r;
cout << "area of circle is";
cout << a;
return 0;
}

c++ class passing member function issues

In class were learning about classes and structures, Im working on a program that is supposed to have to member functions in the class, one doing calculations and one to return certain values, it seems Im running into trouble calling the functions maybe? IM not a 100% sure because c++ cant specify the error. I hope you can help me, thank you in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
void rocket(double massR,double massE, double massP,double avgTh,double bd);
double rocketreturn(double& MV,double& MA);
class Rocket
{
private:
double massR;
double massE;
double massP;
double avgTh; // average thrust
double bd; //burn duration
public:
void rocket(double massR,double massE, double massP,double avgTh,double bd)
{
massR=massR/1000;
massE=massE/1000;
massP=massP/1000;
double LM=massR+massE;
double MCP=massR+massE-massP;
double AM=(LM+MCP)/2;
double acc=(avgTh/AM)-9.8;
double MV= acc * bd;
double Alt=.5*acc*.5*.5;
double t=MV/9.8;
double MA=Alt+MV*t+.5*-9.8*t*t;
}
double rocketreturn(double& MV, double& MA)
{
cout<< MV;
cout<< MA;
}
};
int main( )
{
double massR; // mass of the rocket
double massE; // mass of the engine
double massP; // mass of the propellant
double avgTh; // average thrust
double bd; // burn duration
double MV; // max velocity
double MA; // max altitude
char ans;
system("CLS");
cout << "Take Home # by - "
<< "Rocket Object\n\n";
do
{
cout <<"Enter the mass of the rocket: "<<endl;
cin >> massR;
cout <<"Enter the mass of the engine: "<<endl;
cin >> massE;
cout <<"Enter the mass of the propellant: "<<endl;
cin >> massP;
cout <<"Enter the average thrust of the engine: "<<endl;
cin >> avgTh;
cout <<"Enter the burn duration of the engine: "<<endl;
cin >> bd;
rocketreturn(MV,MA);
cout <<"the rockets maximum velocity is " << MV<<endl;
cout <<"the rockets maximum altitude is "<<MA<<endl;
cout <<"Would you like to run the program again (Y or N)?"<<endl;
cin>>ans;
}
while(ans=='y'||ans=='Y');
}
You can try using the following program structure and fill in the details the way you wish. Note, it won't compile.
#include <iostream>
using namespace std;
class Rocket {
private:
double mR, mE;
public:
/* Constructor. It is missing in your program. You probably want it */
Rocket(double massR, double massE) {
/* Better to use initialization list, but this should work too */
mR = massR;
mE = massE;
}
double rocketreturn(double & a, double & b) {
/* Do sth with the parameters. But return a double,
which you are not doing in your program */
double result = a + b;
return result;
}
};
int main() {
double x, y;
do {
cin >> x >> y;
Rocket my_rocket(x, y);
double z = my_rocket.rocketreturn(x, y); // Assignment not necessary
} while ( /* some condition */) //my_rocket object will be destroyed after scope goes out
return 0;
}

How to reduce/simplify fractions completely (C++)

I cannot for the life of me fathom why I'm getting infinite values returned when I input a normal fraction into the code. Everything but the GCD (Greatest common divisor) seems to be working.
Is there a blatantly obvious logic error somewhere within this?
I've done my research and found various answers to the question, I mean Wikipedia even GIVES YOU code to do it, but I'd like to figure out how to make it work the way I've coded it the way it is now.
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <math.h>
using namespace std;
class Fraction
{
private:
double num;
double den;
double fraction;
double temp;
public:
void setNum();
void setDen();
int getNum();
int getDen();
void lcdOutput();
void decOutput();
int gcd();
};
void Fraction::setNum(){
cout << "Enter a value for your numerator: " << endl;
cin >> num;
}
void Fraction::setDen(){
cout << "Enter a value for your denominator: " << endl;
cin >> den;
}
int Fraction::getNum(){
return num;
}
int Fraction::getDen(){
return den;
}
int Fraction::gcd(){
Fraction set;
if(num > den){
if(fmod(num, den) == 0){
den = temp;
return temp;
}
else{
den = fmod(num, den);
set.gcd();
}
}
else{
if(fmod(den, num) == 0){
num = temp;
return temp;
}
else{
num = fmod(den, num);
set.gcd();
}
}
}
void Fraction::lcdOutput(){
Fraction set;
set.gcd();
num = num / temp;
den = den / temp;
cout << "Fraction in lowest terms: " << num << "/" << den << endl;
}
void Fraction::decOutput(){
double decimal = num / den;
cout.precision(4);
cout << "The fraction in decimal form is: " << decimal << endl;
}
int main(){
Fraction set;
set.setNum();
set.setDen();
set.getNum();
set.getDen();
set.lcdOutput();
set.decOutput();
return 0;
}
Here's what I can determine just by stepping through your code.
Starting at main, you instantiate an instance of type Fraction named set. You assign its numerator and denominator via calls to set.setNum() and set.setDen(). The calls to getNum() and getDen() do nothing in this case, as they are not being assigned to anything.
Then you call lcdOutput(), so let us begin stepping through that.
You begin by instantiating a LOCAL instance of Fraction (not sure why you want to do this, it appears to me that this may be a conceptual mistake), and then call set.gcd() for that local instance. Calling set.gcd() will call the method for THAT INSTANCE, and it seems to me that what you really want is this->gcd() or simply gcd().
You follow up by setting num = num / temp and den = den / temp, but temp is still uninitialized at this point. If the variable is left uninitialized, it can (and usually is) pointing to garbage. This probably explains why you are getting nonsensical values returned.
I went back and figured it out on my own. I saw some of the comments and noticed my very large conceptual and logical errors. Here's to anyone that has the same question!
int gcd(double num, double den){
if(den == 0){
return num;
}
return gcd(den, fmod(num, den));
}
void Fraction::lcdOutput(){
double temp = gcd(num, den);
cout << "Fraction in lowest terms: " << num / temp << "/" << den / temp << endl;
}