I'm learning C++, and to do that I have created myself a problem which is to convert Celsius to Fahrenheit three times in the console. The user will input the Celsius degree.
I also want the output to be displayed like this:
Celsius: Fahrenheit:
cel1 fahr1
cel2 fahr2
cel3 fahr3
The code I have tried so far is:
double cel1, cel2, cel3;
double fahr1, fahr2, fahr3;
cout << "Celsius degree one: ";
cin >> cel1;
cout << "Celsius degree two: ";
cin >> cel2;
cout << "Celsius degree three: ";
cin >> cel3;
fahr1 = (cel1 * 9) / 5 + 32;
fahr2 = (cel2 * 9) / 5 + 32;
fahr3 = (cel3 * 9) / 5 + 32;
// messy like this to display like I want to
cout << endl <<
"Celsius: " << "Fahrenheit:" << endl <<
cel1 << " " << fahr1 << endl <<
cel2 << " " << fahr2 << endl <<
cel3 << " " << fahr3 << endl << endl;
which will display like I want to, but I feel this could have been achieved in a simpler way, so I tried something like this with a loop, but I couldn't figure out how to do it properly:
double celsius;
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius;
double fahrenheit = (celsius * 9) / 5 + 32;
cout << "Fahrenheit degree: " << fahrenheit << endl;
cin.clear();
}
This code is less then the previous one, gives the correct answer and will convert three times, but I couldn't figure out how to display it like I want to.
My question is what is the best way to do this?
I suggest to split the code into smaller functions:
The one to compute the conversion
double celsius_to_fahrenheit(double celsius)
{
return (celsius * 9.0) / 5.0 + 32.0;
}
The one to get the input, I choose to use std::vector as container.
you may choose std::array<double, 3> since the array have fixed size,
but std::vector is a good default choice.
std::vector<double> get_input_celsius(std::size_t size)
{
std::vector<double> celsius(size);
for (std::size_t i = 0; i != celsius.size(); ++i) {
std::cout << "Celsius degree " << (i + 1) << ": ";
std::cin >> celsius[i];
}
return celsius;
}
The method to display the result. I choose to not store the conversion in a new std::vector since it is not used afterward:
void display_celsius_and_fahrenheit(const std::vector<double>& celsius)
{
std::cout << std::endl << "Celsius: " << "Fahrenheit:" << std::endl;
for (auto c : celsius) { // for range since C++11
std::cout << c << " " << celsius_to_fahrenheit(c) << std::endl;
}
}
And finally the main function:
int main()
{
std::vector<double> celsius = get_input_celsius(3);
display_celsius_and_fahrenheit(celsius);
return 0;
}
Live example
Create arrays to store the temperatues.
Instead of
double cel1, cel2, cel3;
double fahr1, fahr2, fahr3;
use
double celsius[3];
double fahrenheit[3];
Change the input gathering loop to use the arrays.
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius[times];
fahrenheit[times] = (celsius[times] * 9) / 5 + 32;
cin.clear();
}
Use a loop to create the output:
cout << endl << "Celsius: " << "Fahrenheit:" << endl <<
for (int times = 0; times != 3; ++times){
cout << celsius[times] << " " << fahrenheit[times] << endl;
}
You could get away with not creating the array fahrenheit too if you compute it only during output.
In that case, change the input gathering loop to:
for (int times = 0; times != 3; ++times){
cout << "Celsius degree: ";
cin >> celsius[times];
cin.clear();
}
Change the output loop to:
cout << endl << "Celsius: " << "Fahrenheit:" << endl <<
for (int times = 0; times != 3; ++times){
double fahrenheit = (celsius[times] * 9) / 5 + 32;
cout << celsius[times] << " " << fahrenheit << endl;
}
Related
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main()
{
int caltype;
int numorden;
int length, angle;
cout << "Type '1' for sine, '2' for cosine and '3' for tangent." << endl;
cin >> caltype;
switch (caltype) {
case 1:
cout << "Is the unknown length the numerator or the denominator? Type '1' for numerator and '2' for denominator." << endl;
cin >> numorden;
switch (numorden) {
case 1:
cout << "Type the length of the hypotenuse." << endl;
cin >> length;
cout << "Type in the angle." << endl;
cin >> angle;
cout << "sinangle = O/H" << endl;
cout << "sin" << angle << " = x/" << length << endl;
cout << length << "sin" << angle << " = x" << endl;
cout << "Therefore x = " << length *sin (angle);
break;
case 2:
cout << "Type the length of the opposite." << endl;
cin >> length;
cout << "Type in the angle." << endl;
cin >> angle;
cout << "sinangle = O/H" << endl;
cout << "sin" << angle << " = " << length << "/x" << endl;
cout << "xsin" << angle << " = " << length << endl;
cout << "Therefore x = " << length / sin (angle);
}
}
}
What I am making right now is a program that will show you the steps when it is doing trigonometry. For some reason, when the opposite is divided by, lets say, sin(30), it always results in a negative number. Why is that? The error appears to be occurring at this line:
cout << "Therefore x = " << length / sin (angle);
You need to convert it to radians:
sin (angle * PI/180);
UPDATE:
What is PI?
World Record values of PI
The sin function takes input as radian:
sin (angle * M_PI/180);
where M_PI = 3.141...., which is a constant.
I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link
please see my code below and let me know what I'm not seeing. I've tried almost everything to make it work and nothing yet.
Thanks in advance for your time and help.
for (double c = c1; c <= c2; c = c + i)
{
cout << "Enter the lowest temperature: " << endl;
cin >> c1;
cout << "Enter the highest temperature: " << endl;
cin >> c2;
cout << "Enter the desired increment in temperature: " << endl;
cin >> i;
f = ((9 / 5) * c) + 32;
cout << "When C is " << c << " degrees Celsius, the temperature in Fahrenheit will be: " << f << " degrees." << endl;
cin.get();
}
return 0;
}
You take the input in the wrong part of the code.
c1 and c2 were probably never assigned before the loop, and your logic as reflected in the codedoesn't seem to match your intentions as it changes the loop limit every time.
Also, note using 9.0 instead of 9 to get a double result and not an integer.
See full example here https://ideone.com/Uj974z.
int main() {
double c1, c2, i, f;
cout << "Enter the lowest temperature: " << endl;
cin >> c1;
cout << "Enter the highest temperature: " << endl;
cin >> c2;
cout << "Enter the desired increment in temperature: " << endl;
cin >> i;
for (double c = c1; c <= c2; c = c + i)
{
f = ((9.0 / 5) * c) + 32;
cout << "When C is " << c << " degrees Celsius, the temperature in Fahrenheit will be: " << f << " degrees." << endl;
}
return 0;
}
The problem is that 9/5 returns 1. You should write 9.0/5.
Hey so the code I made should be working to calculate the passer rating for quarterbacks in the NFL. The program, however, returns a value of 0 for almost anything, unless I put ridiculously large numbers, in which case it gives 100. What's wrong with it?
#include <iostream>
using namespace std;
int main()
{
int PassCompletions;
cout << "Enter pass completions" << endl;
cin >> PassCompletions;
int PassAttempts;
cout << "Enter pass attempts" << endl;
cin >> PassAttempts;
int TotalPassY;
cout << "Enter total yards" << endl;
cin >> TotalPassY;
int Touch;
cout << "Enter touchdowns" << endl;
cin >> Touch;
int Int;
cout << "Enter interceptions" << endl;
cin >> Int;
int C = (PassCompletions/PassAttempts-0.30)*5;
int Y = (TotalPassY/PassAttempts-3)*0.25;
int T = (Touch/PassAttempts)*20;
int I = 2.375 - (Int/PassAttempts*25);
if (C<0){
C=0;
}
if (Y<0){
Y=0;
}
if (T<0){
T=0;
}
if (I<0){
I=0;
}
if (C>2.375){
C=2.375;
}
if (Y>2.375){
Y=2.375;
}
if (T>2.375){
T=2.375;
}
if (I>2.375){
I=2.375;
}
int PasserRating = (C+Y+T+I)/6*100;
if (PasserRating <= 85){
cout << "Rating " << PasserRating << ", this is poor" << endl;
}
if (PasserRating > 85 && PasserRating < 90){
cout << "Rating " << PasserRating << ", this is mediocre" << endl;
}
if (PasserRating > 90 && PasserRating < 95){
cout << "Rating " << PasserRating << ", this is good" << endl;
}
if (PasserRating > 95){
cout << "Rating " << PasserRating << ", this is great" << endl;
}
You need use data type which is suitable to store fractional value. For this purpose use float instead of int for these statements:
float C = (PassCompletions/PassAttempts-0.30)*5;
float Y = (TotalPassY/PassAttempts-3)*0.25;
float T = (Touch/PassAttempts)*20;
float I = 2.375 - (Int/PassAttempts*25);
The variable type int is only used to store whole numbers, eg 1,2,3...
Any expression with a decimal will be truncated and rounded down. Since you are doing a lot of calculations with floating point numbers, eg. 2.375, I would suggest you changing your int's to float's
I have quite straight forward question. The following code prints out celsius and fahrenheit.
My question is though about number of times it iterate. For a small number e.g. start 0, stop at 10, with a step of 1.1. After the loop is finished it will print out the correct number of iterations it made.
But for large number 0-11000000, with step 1.1 it will print out wrong number of iteration. Why is that happening? Since 1100000/1.1 should be around 1000001, but I get 990293.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float start, stop, step;
int count = 0;
cout << "start temperature: ";
cin >> start;
cout << "stop temperature: ";
cin >> stop;
cout << "step temperature: ";
cin >> step;
cout << setw(10) << "celsius" << setw(15) << "fahrenheit" << endl;
cout << setw(25) << "celsius" << setw(15) << "fahrenheit" << endl;
while(start <= stop)
{
count++;
float c, f;
c = (5.0/9)*(start-32);
f = 32+(9.0/5)*start;
cout << setw(10) << fixed << setprecision(2) << c << setw(15) << start << setw(15) << fixed << setprecision(2) << f << " count: " << count << endl;
start = start + step;
}
cout << "The program loop made " << count << " iterations." << endl;
return 0;
}
Floating-point rounding error. Essentially, floats are not a 100% accurate representation, there are errors in every calculation you make, and as you repeatedly add to them, you will be adding more and more error. What you should do is compute the number of steps once, store it in an integer, and then loop that many times.
For the record, a cleaned-up version would look like:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double start, stop, step;
cout << "start temperature: ";
cin >> start;
cout << "stop temperature: ";
cin >> stop;
cout << "step temperature: ";
cin >> step;
cout << setw(10) << "celsius" << setw(15) << "fahrenheit" << endl;
unsigned steps = (stop - start) / step;
for(unsigned i = 0; i < steps; ++i)
{
double temp = start + i * step;
double c = (5.0 / 9.0) * (temp - 32.0);
double f = 32.0 + (9.0 / 5.0) * temp;
// This is a real good example of why people hate <iostream> formatting.
// If you want formatting that's quite different from the default, it
// gets too verbose too fast. Using C stdio:
//printf("%10.2f%15.2f\n", c, f);
cout << setw(10) << fixed << setprecision(2) << c
<< setw(15) << fixed << setprecision(2) << f << endl;
}
cout << "The program loop made " << steps << " iterations." << endl;
return 0;
}
The main benefit of this style of loop is that each iteration is (except for the output) order-independent, so it could be unrolled and (theoretically) parallelized.