Trying to add fractions while also printing LCD - c++11

I'm a beginner trying to figure out this program of adding fractions while also making their output print the result in it's lowest common denominator form. Running it in this form never runs properly...
using namespace std;
class Fraction { //Creates class Fraction
private: //Makes data members private
int num;
int denm;
};
int main()
{
int num;
int denm;
int num2;
int denm2;
int plus;
int plus2;
cout << "Please enter the numerator and denominator of the first fraction: " << endl;
cin >> num >> denm;
cout << "Please enter the numerator and denominator of the second fraction: " << endl;
cin >> num2 >> denm2;
plus = num*denm2 + denm*num2;
plus2 = denm*denm2;
cout << num << "/" << denm << " + " << num2 << "/" << denm2 << " = " << plus << "/" << plus2;
cout << "Hit 'enter' to exit..." << endl;
}

You'll need to run the program in a fashion that keeps the output window open or modify it to accomplish this. See here for examples:
How to keep the console window open in Visual C++?
One way to do this in any environment would be to cin another value before the final return 0 - this would, of course, require you to press something other than enter first, but it serves the purpose.

Related

I have written a program for Type Conversion (Primitive to class type) . When I am running this on DEV its showing me garbage value

#include < iostream >
#include < iomanip >
using namespace::std;
#include < string.h >
class Human {
char Name[20];
int Age;
float Weight;
public:
Human() {
strcpy(Name, " ");
Age = Weight = 0;
}
Human(int AGE) {
this - > Age = Age;
}
Human(float Weight) {
this - > Weight = Weight;
}
Human(char * s) {
strcpy(this - > Name, s);
}
void GetData() {
cout << endl << "Enter the name : ";
gets(Name);
cout << endl << "Enter the Age : ";
cin >> Age;
cout << endl << "Enter the Weight :";
cin >> Weight;
}
void Display() {
cout << endl << "Name :" << Name;
cout << endl << "Age :" << Age;
cout << endl << fixed << "Weight :" << Weight << " Kg";
}
};
int main() {
Human h1;
h1 = 23; //It will assign 23 in Age
h1 = 67.45 f; //It will assign 67.45 in Weight
h1 = "Jimmy Neutron";
h1.Display();
cin.get();
return 0;
}
There are several issues here but let me start with the one you asked.
Why is the output like this:
Name :Jimmy Neutron Age :4194304 Weight :0.000000 Kg – Udesh
The reason is every time you assign values like this to your object i.e., h1
h1 = 23; //It will assign 23 in Age
h1 = 67.45f; //It will assign 67.45 in Weight
h1 = "Jimmy Neutron";
This is what is happening behind the scene, move assignment operator gets called.
h1.operator=(Human(23));
h1.operator=(Human(67.4499969f));
h1.operator=(Human("Jimmy Neutron"));
So, the other two arguments get overwritten everytime you write one of this.
To understand the problem, try using your display function after every assignment statement and see the output.
Now lets come to other issues.
Please avoid using char array and char pointer. We have the wonderful std::string for the very same purpose, please use it. IIRC, every major compiler warns about string literal to char * conversion.
I do not know if you realized, but the parameter name in one of your constructor that takes int is AGE but you are assigning age.
Please avoid using deprecated functions - [hint: gets]

Possible rounding error? C++

I'm still very new to c++, so forgive me if this should is an ignorant question. The purpose of this short code is to calculate a monthly car payment based on 6 user inputs.
Using these inputs, 623.72 is output, however I was expecting 626.81
Inputs, in order: 20000,
0.06,
1000,
100,
0.07,
36.
Can anyone shed any light on why my answer is slightly off? Am I running into a rounding error? Am I rounding in the wrong place or using a wrong variable type?
Thanks!
The formula for monthly payment is broken down into steps which made it easier to write. It's based off this formula:
monthly_payment =
Final_price_minus_downpayment * ( (monthly_rate * (1 + monthly_rate)^num_months / (1 + monthly_rate)^num_months - 1 )
#include <iostream>
#include <iomanip>
#include <cmath>
using std::cout;
using std::cin;
using std::endl;
using std::pow;
using std::fixed;
using std::setprecision;
int main() {
//Initializing the 6 user inputs
double carPrice;
double salesTaxRate;
double downPayment;
double titleAndFees;
double yearlyInterestRate;
double loanDuration;
//Getting the 6 user inputs
cin >> carPrice;
cin >> salesTaxRate;
cin >> downPayment;
cin >> titleAndFees;
cin >> yearlyInterestRate;
cin >> loanDuration;
//Calculate the monthly Payment
double salesTax = carPrice * salesTaxRate;
double totalPrice = carPrice + salesTax;
double finalPriceMinusDown = totalPrice - downPayment;
double monthlyInterestRate = yearlyInterestRate / 12.0;
//Formula broken down into steps
double step1 = pow((1+monthlyInterestRate),loanDuration);
cout << step1 << endl;
double step2 = monthlyInterestRate * step1;
cout << step2 << endl;
double step3 = step1 - 1;
cout << step3 << endl;
double step4 = step2 / step3;
cout << step4 << endl;
double step5 = finalPriceMinusDown * step4;
cout << step5 << endl;
double monthlyPayment = step5;
//cout << "The monthly payment is: ";
cout << fixed << setprecision(2) << monthlyPayment;
}

C ++ , My for loop doesn't work when I run it on the terminal. Any ideas?

When I run it on the terminal it works fine but the loop. The for loop just doesn't do anything at all. I'm learning C++, so I don't know much.
#include <iostream>
#include <cstring>
using namespace std;
int main( int argc, char *argv[] ) {
if (argc == 2) {
cout << "The first argument is " << argv[0] << endl;
cout << "The second argument is " << argv[1] << endl;
} else if (argc > 2) {
cout << "Too many arguments" << endl;
exit(0);
} else {
cout << "Only one argument" << endl;
cout << "The argument is " << argv[0] << endl;
exit(0);
}
if (atoi(argv[1]) < 0) {
cout << "Error negative number" << endl;
exit(0);
}
// this loop does not work, everything else does.
for (int i = 1; i >= atoi(argv[1]); i++){
int count = atoi(argv[1]--);
cout << count << endl;
int sum = sum + i;
}
cout << "The sum is: " << endl;
return(0);}
I think that could be the if statements what are messing around with the loop.
I think you made mistake in the for loop.
You show use "<=" instead of ">=" in the for loop.
Hope this might helps you.
I guess your code is not reaching the for loop as you have exit() conditions on each and every condition of if. Your code only reaches the loop if you are passing 2 arguments in the terminal while you are running your code

Linear interpolation is not working as expected

I have a map that represents the values of a coefficient Y for a given range of temperatures. I'm trying to get the coeff_Y whenever the input key designTempfalls anywhere between the upper and lower limits of keys. I was able to get the three cases: a) when the value of the input designTemp is below the first key then coeff_Y is the first value, b) if the value of the input designTemp is beyond the last key then coeff_Y is the last value and c) if designTemp matches a key then the coeff_Y becomes the corresponding value. The case if the key falls anywhere within the key range is not working. The code showing the failed attempt of interpolation is shown below. Please note that I'm not a programmer, I'm a piping engineer just trying to write my own programs and trying to become proficient at coding with C++. Also, if there is any better solution please show so.
`cout << "\n Enter design temp. in degF: ";
float designTemp;
cin.clear(); cin.ignore(10000, '\n'); cin >> designTemp;
map<float, float> ferriticsteels_Y = { {900, 0.4}, {950, 0.5}, {1000, 0.7} };
if (ferriticsteels_Y.find(designTemp) != ferriticsteels_Y.end())
{
float coeff_Y = ferriticsteels_Y[designTemp];
cout << "\n Y: " << coeff_Y << endl;
}
if (designTemp < ferriticsteels_Y.begin()->first)
{
float coeff_Y = ferriticsteels_Y.begin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
if (designTemp > ferriticsteels_Y.rbegin()->first)
{
float coeff_Y = ferriticsteels_Y.rbegin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
auto lower = ferriticsteels_Y.lower_bound(designTemp) == ferriticsteels_Y.begin() ? ferriticsteels_Y.begin() : --(ferriticsteels_Y.lower_bound(designTemp));
auto upper = ferriticsteels_Y.upper_bound(designTemp);
float coeff_Y = lower->second + (upper->second - lower->second) * float(designTemp - lower->first)/fabs(upper->first - lower->first);
time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << "\n" << asctime(timeinfo_end);
cout << "\nEnter any character and hit enter to exit: ";
char ans;
//cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> ans;...giving error at 'max()'
cin.clear(); cin.ignore(10000, '\n'); cin >> ans;
return 0;}`
It works. I just was making stupid mistake. It only required to revise the nesting of the if-statements and to add a cout for looking the interpolated value at the last else. Below is the code which works as expected:
#include "../../std_lib_facilities.h"
#include <Windows.h>
#include <map>
int main()
{
SetConsoleTitle(TEXT("PipeTran™_v0.1"));
system("CLS");
system("color F1");
time_t rawtime_start;
struct tm * timeinfo_start;
time(&rawtime_start);
timeinfo_start = localtime(&rawtime_start);
printf(asctime(timeinfo_start));
cout << "\n Enter design temp. in degF: ";
float designTemp;
cin >> designTemp;
map<float, float> ferriticsteels_Y = { { 900, 0.4 },{ 950, 0.5 },{ 1000, 0.7 } };
if (ferriticsteels_Y.find(designTemp) != ferriticsteels_Y.end()) {
float coeff_Y = ferriticsteels_Y[designTemp];
cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp < ferriticsteels_Y.begin()->first) {
float coeff_Y = ferriticsteels_Y.begin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp > ferriticsteels_Y.rbegin()->first) {
float coeff_Y = ferriticsteels_Y.rbegin()->second;
cout << "\n Y: " << coeff_Y << endl;
}
else {
auto lower = ferriticsteels_Y.lower_bound(designTemp) == ferriticsteels_Y.begin() ? ferriticsteels_Y.begin() : --(ferriticsteels_Y.lower_bound(designTemp));
auto upper = ferriticsteels_Y.upper_bound(designTemp);
float coeff_Y = lower->second + (upper->second - lower->second) * float(designTemp - lower->first) / fabs(upper->first - lower->first);
cout << "\n Y: " << coeff_Y << endl;
}
time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << "\n" << asctime(timeinfo_end);
cout << "\nEnter any character and hit enter to exit: ";
char ans;
cin.clear(); cin.ignore(10000, '\n'); cin >> ans;
return 0;
}

How to use SetConsoleTextAttribute C++

I have searched countless forums and websites but I can't seem to find the answer. I'm trying to use SetConsoleTextAttribute but it only affects the text. How can I affect the whole screen like the command color 1f would? My code is:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincon.h>
using namespace std;
int main()
{
SetConsoleTitle("C++ CALCULATOR"); // Title of window
int x; // Decision
int a; // First Number
int b; // Second Number
int c; // Answer
HANDLE Con;
Con = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(Con, BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
cout << "CALCULATOR" << endl << endl;
cout << "1:ADDITION" << endl << "2:SUBTRACTION" << endl << "3:MULTIPLICATION";
cout << endl << "4:DIVISION" << endl << "5:EXIT" << endl;
cin >> x;
switch (x)
{
case 1: // Addition code
cout << endl << "ADDITION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a + b;
cout << endl << "ANSWER:" << c;
break;
case 2: // Subtraction code
cout << endl << "SUBTRACTION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a - b;
cout << endl << "ANSWER:" << c;
break;
case 3: // Multiplication code
cout << endl << "MULTIPLICATION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a * b;
cout << endl << "ANSWER:" << c;
break;
case 4: // Division code
cout << endl << "DIVISION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a / b;
cout << endl << "ANSWER:" << c;
break;
case 5: // Exit code
return 0;
}
}
This solution relies on these WinAPI functions and structures:
GetConsoleScreenBufferInfo to get screen dimensions
FillConsoleOutputAttribute to fill screen with an attribute
CONSOLE_SCREEN_BUFFER_INFO structure to store screen information
The code is as follows:
HANDLE hCon;
CONSOLE_SCREEN_BUFFER_INFO csbiScreenInfo;
COORD coordStart = { 0, 0 }; // Screen coordinate for upper left
DWORD dwNumWritten = 0; // Holds # of cells written to
// by FillConsoleOutputAttribute
DWORD dwScrSize;
WORD wAttributes = BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
// Get the screen buffer information including size and position of window
if (!GetConsoleScreenBufferInfo(hCon, &csbiScreenInfo))
{
// Put error handling here
return 1;
}
// Calculate number of cells on screen from screen size
dwScrSize = csbiScreenInfo.dwMaximumWindowSize.X * csbiScreenInfo.dwMaximumWindowSize.Y;
// Fill the screen with the specified attribute
FillConsoleOutputAttribute(hCon, wAttributes, dwScrSize, coordStart, &dwNumWritten);
// Set attribute for newly written text
SetConsoleTextAttribute(hCon, wAttributes);
The inline comments should be enough to understand the basics of what is going with the supplied documentation links. We get the screen size with GetConsoleScreenBufferInfo and use that to determine the number of cells on the screen to update with a new attribute using FillConsoleOutputAttribute . We then use SetConsoleTextAttribute to ensure that all new text that gets printed matches the attribute we used to color the entire console screen.
For brevity I have left off the error check for the calls to FillConsoleOutputAttribute and SetConsoleTextAttribute. I put a stub for the error handling for GetConsoleScreenBufferInfo . I leave it as an exercise for the original poster to add appropriate error handling if they so choose.
SetConsoleTextAttribute changes the attribute for new characters that you write to the console, but doesn't affect existing contents of the console.
If you want to change the attributes for existing characters already being displayed on the console, use WriteConsoleOutputAttribute instead.

Resources