I just started to study informatics. Now i got my first task and i,am full of questions. Does someone have some advice for me?
The task is to create an math formula which allows to decide between 3 different formula without any kind of "switch, if-else or other operators"
Sooo goal is it to just
cin a number;
decide with cin 1, 2 or 3 between Celsius to Fahrenheit, meters in foot or € in $ and gettin a result. Im pretty new and just asking me for like 2 hours what such a formula would look like D:
any idea?
My Actual Code looks like this. (we arent allowed to use any kind of code we hadnt in our lectures yet. Allowed are just: value assignment, variables, simply data types , basic calculus, cins and couts..
Im just curious on that formula which does not get into my head and how to code it...
#include <iostream>
using namespace std;
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
system("PAUSE");
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
system("PAUSE");
}
If Yasir's solution still uses features that aren't to your teacher's liking (operator == might be forbidden as well), the remaining solution is polynomial regression...
#include <iostream>
int main()
{
//zahleneingabe
std::cout << "Ihre Eingabe: ?\n";
double eingabe;
std::cin >> eingabe;
std::cout << "Ihre Eingabe: " << eingabe << '\n';
//abfragenausgabe der umrechnungsart
std::cout << "Ihre Auswahl der Umwandlung:\n";
std::cout << "1 - Celsius in Fahrenheit\n";
std::cout << "2 - Meter in Fuss\n";
std::cout << "3 - Euro in US Dollar\n";
int auswahl;
std::cin >> auswahl;
// Found using http://www.xuru.org/rt/PR.asp (ain't nobody got time for that)
double const coefficient = (-1.82584 * auswahl + 6.95836) * auswahl - 3.33252;
double const offset = (16.0 * auswahl - 80.0) * auswahl + 96.0;
double const ergebnis = eingabe * coefficient + offset;
std::cout << "Ihr Ergebnis ist: " << ergebnis << '\n';
}
Note that I have also cleaned up the code by removing using namespace std;, rescoping variables to their actual use, and added const where relevant. I leave it to you to translate the new variables to german ;)
See it live on Wandbox
You could also use modulo to your advantage.
Assume the formulae:
const float fahrenheitConst = 9.f/5.f;
const float feetConst = 3.2f;
const float exchangeRate = 1.11f;
// eingabe = x, auswahl = y
double a = x * fahrenheitConst + 32;
double b = x * feetConst;
double c = x * exchangeRate;
double result = ( y % 3 ) * ( y % 2 ) * a + ( ( y + 2 ) % 3 ) * ( y + 1 ) % 2 * b + ( y + 1 ) % 3 * ( ( y - 1 ) / 2 ) * c
Explanation
Basically we want a formula, that is a sum of three terms, where each term is the result of a subformula and two coefficients. For every input, the coefficients for one of the three terms must result in 1 each, while the coefficients for the other two terms must include at least one 0 coefficient per term. To put differently, we want only one of the three subformulae a, b or c to be part of result and its magnitude needs to be exactly 1.
y % 3 results in 0 for 3 and in 1 for 1
y % 2 results in 0 for 2 and in 1 for 1
( y + 2 ) % 3 results in 0 for 1 and in 1 for 2
( y + 1 ) % 2 results in 0 for 3 and in 1 for 2
( y + 1 ) % 3 results in 0 for 2 and in 1 for 3
( ( y - 1 ) / 2 ) results in 0 for 1 and in 1 for 3 (cannot use % 1)
Demonstration
Let input be 1:
result = ( 1 % 3 ) * ( 1 % 2 ) * a + ( ( 1 + 2 ) % 3 ) * ( 1 + 1 ) % 2 * b + ( 1 + 1 ) % 3 * ( ( 1 - 1 ) / 2 ) * c
= 1 * 1 * a + 0 * 0 * b + 1 * ( 0 / 2 ) * c
= 1 * a + 0 * b + 0 * c
= a
Let input be 2:
result = ( 2 % 3 ) * ( 2 % 2 ) * a + ( ( 2 + 2 ) % 3 ) * ( 2 + 1 ) % 2 * b + ( 2 + 1 ) % 3 * ( ( 2 - 1 ) / 2 ) * c
= 1 * 0 * a + 1 * 1 * b + 0 * [1/2 --> 0 in INT] * c
= 0 * a + 1 * b + 0 * c
= b
Let input be 3:
result = ( 3 % 3 ) * ( 3 % 2 ) * a + ( ( 3 + 2 ) % 3 ) * ( 3 + 1 ) % 2 * b + ( 3 + 1 ) % 3 * ( ( 3 - 1 ) / 2 ) * c
= 0 * 1 * a + 2 * 0 * b + 1 * 1 * c
= 0 * a + 0 * b + 1 * c
= c
Notes
There is an ambiguity in the division, that depends on the types used, this is where I wrote [1/2 --> 0 in INT]. That is because for float or double this results in 1/2, but for int this results in 0. Please note how this makes absolutely no difference here. The result could be 5000, but as long as the previous factor results in 0, the whole term resolves to 0.
Additionally you could use integer division to your advantage, i.e. dividing a smaller numer by a larger number will result in 0 for int . I chose not to go that way, because OP mentioned a mathematical solution, while taking advantage of integer division is rather a programmatical approach.
Conclusion
Use:
result = c1 * c2 * formula1 + c3 * c4 * formula2 + c5 * c6 * formula3
So that only the coefficients c_i for one of the three formulae resolve to exactly 1 each, while for the other coefficients at least one per formula must resolve in 0.
I think this should solve your problem. I can't think of anything else that solves it.
#include <iostream>
using namespace std;
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
double feet_conv = 3.28084;
double dollar_conv = 1.11;
ergebnis = (auswahl == 1) * ((eingabe * 9.0 / 5) + 32) +
(auswahl == 2) * eingabe * feet_conv +
(auswahl == 3) * eingabe * dollar_conv;
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
return 0;
}
Can do without if/switch or ternary operator, or comparison, just boolean operations, implicit bool-to-integer conversion, and multiplication:
#include <iostream>
using namespace std;
double c_zu_f(double in) { return in * (9.0/5.0) + 32.0; }
double m_zu_ft(double in) { return 3.0 * in; } // approx.
double eur_zu_usd(double in) { return 1.2 * in; } // approx.
int main()
{
double eingabe;
int auswahl = 0;
double ergebnis;
//zahleneingabe
cout << "Ihre Eingabe: ? " << endl;
cin >> eingabe;
cout << "Ihre Eingabe: " << eingabe << endl;
system("PAUSE");
//abfragenausgabe der umrechnungsart
cout << "Ihre Auswahl der Umwandlung: " << endl;
cout << "1 - Celsius in Fahrenheit" << endl;
cout << "2 - Meter in Fuss" << endl;
cout << "3 - Euro in US Dollar " << endl;
cin >> auswahl;
bool auswahl_gueltig = auswahl && (auswahl & 0x03); // oder nur (auswahl & 0x03), da 0 --> false
bool auswahl_ist_eins = auswahl_gueltig && ( (auswahl & 1) && !(auswahl & 2));
bool auswahl_ist_zwei = auswahl_gueltig && (!(auswahl & 1) && (auswahl & 2));
bool auswahl_ist_drei = auswahl_gueltig && !( auswahl_ist_eins || auswahl_ist_zwei );
ergebnis = auswahl_ist_eins * c_zu_f(eingabe) + auswahl_ist_zwei * m_zu_ft(eingabe) + auswahl_ist_drei * eur_zu_usd(eingabe);
cout << "Ihr Ergebnis ist: " << ergebnis << endl;
system("PAUSE");
}
If given invalid (not 1, 2, or 3) auswahl, the result shown will be zero, but that's as good as you can get without if or ternary operator (though you could assert(auswahl_gueltig) of course, which isn't exactly the same but at least won't fail silently).
Can make the implicit bool to int conversion explicit with a cast, too, if you like -- but that's unnecessary and ugly.
Give an integer named choice representing the user's choice, the following expression evaluates to 0 when the the user chooses 1 or 2 and it evaluates to 1 when the user chooses 3:
(choice - 1) * (choice - 2) * 0.5
Therefore, this expression is a pretty good replacement for choice == 3, which you are not allowed to use in this homework problem because it contains ==.
With the hint above, you can probably guess what to do. But here is a complete solution:
#include <iostream>
int main()
{
double input;
std::cout << "Enter your input: " << std::endl;
std::cin >> input;
int choice;
std::cout << "Choose your conversion: " << std::endl;
std::cout << "1: Celsius to Fahrenheit" << std::endl;
std::cout << "2: Meters to feet" << std::endl;
std::cout << "3: Euros to US Dollars" << std::endl;
std::cin >> choice;
double result =
(choice - 2) * (choice - 3) * 0.5 * (1.8 * input + 32) + // C to F
(choice - 1) * (choice - 3) * -1 * (3.28084 * input) + // m to ft
(choice - 1) * (choice - 2) * 0.5 * (0.97 * input) // Euro to USD
;
std::cout << "Result: " << result << std::endl;
}
Related
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a , b , c , D ;
double x1 , x2 ;
cout << " a = " ;
cin >> a;
cout << " b = " ;
cin >> b;
cout << " c = " ;
cin >>c;
D = pow(b,2) - 4 * a * c;
x1 = (-b + D ) / (2*a);
x2 = (- b - D) / (2*a);
cout << "D = " << D << endl;
D >= 0 ? ( x1,x2) : (cout << "nope . \n" , x1 = x2 = 0);
cout << x1 << endl;
cout << x2 << endl;
(D % 2) == 1 ? (D++) : (cout << "Number is even . \n" ); //check if number is uneven and if it is then add 1
cout << D << endl;
return 0;
}
it throws the error :operands to ?: have different types 'int' and 'std::basic_ostream' .
At the line where is the comment.
Is it possible to fix it by using the conditional operator (?) ?
As suggested in comments, cast both operands to void:
(D % 2) == 1 ? void(D++) : void(cout << "Number is even . \n" );
Or even better, use a regular if:
if (D % 2 == 1)
D++;
else
cout << "Number is even . \n";
You need to do the same thing for the other use of the ? : as well.
It has been said in the comments of the question already but to clarify on this.
The ternary(?) operator has a return type equal to the type of both code branches if the branches do not return the same type then this error will get shown by the compiler.
A comment use of the ternary operator is to assign a value to a variable depending on a condition:
bool isConnected = true;
static int idCount = 0;
int connectionID = isConnected ? ++idCount : -1;
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i;
const int N = 5;
for (i = 1; i <= N; i++){
double Yn = (1.0 / 2) * (Yn - 1) + (1.0 / 3) * (Yn - 2);
std::cout << i << " " << "= "<< " " << Yn;
std::cout << std::endl;
}
return 0;
}
I have an equation and a table of sequences.
Equation
Y[n] = 1/2*(Y[n-1]) + 1/3*(Y[n-2])
Y[1] = 0.5, Y[2] = 0.4
The table shown below should be printed by using for loops.
N -- Yn
1 -- 0.5
2 -- 0.4
3 -- 0.366667
4 -- 0.316667
5 -- 0.280556
All I have to do is to print the above table .
You wrote down the sequence wrong.
You have:
Yn = 1/2*(Yn - 1) + 1/3*(Yn - 2)
But it should be:
Yn = 1/2*(Yn-1) + 1/3*(Yn-2)
So you need to keep track of the previous two numbers in the sequence to calculate the next one:
int i=1;
const int N = 5;
double Y_prev1 = 0.4;
double Y_prev2 = 0.5;
std::cout << i++ << " " << "= "<< " " << Y_prev2 << std::endl;
std::cout << i++ << " " << "= "<< " " << Y_prev1 << std::endl;
for (; i <= N; i++){
double Y = (1.0 / 2) * (Y_prev1) + (1.0 / 3) * (Y_prev2);
std::cout << i << " " << "= "<< " " << Y;
std::cout << std::endl;
Y_prev2 = Y_prev1;
Y_prev1 = Y;
}
Output:
1 = 0.5
2 = 0.4
3 = 0.366667
4 = 0.316667
5 = 0.280556
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Super new to coding and I've been stuck for awhile on this question. I need to make a program that inputs the temperature in Celsius and an increment that is inputted for a total of 20 lines. In the process it converts to Fahrenheit, Kelvin, and Rankine. That is all fine but I can't get the values to increment by my input.
e.g., As it should look:
Enter temperature in Cel: 50
Enter increment: 5
Cel Far Kel Rank
1 - 50 ...............................
2 - 55 ..............................
3 - 60 ..............................
.
.
.
.
20 - 150 .............................
I can't get the values to increment at all. Being reading my notes and looking online to understand the issue but no luck.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main()
{
int CELS; // celsius entry
int x; // x = input value for increment
double FAH = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << "Enter the temperature in celsius: ";
cin >> CELS;
while ((CELS < -273.15) || (CELS > 5000))
{
cout << "ERROR: out of range." << endl;
cout << "Enter the temperature in celsius: ";
cin >> CELS;
}
cout << "Enter the increment value: ";
cin >> x;
cout << endl;
cout << " # Cels Fahr Kel Rank" << endl;
cout << right;
for (int i = 1; i <= 20; i++)
{ //
for (double j = CELS; j <= CELS; x++)
{ //
for (double k = (CELS * (9.0 / 5) + 32);
k <= (CELS * (9.0 / 5) + 32); x++)
{
for (double m = (CELS + 273.15); m <= (CELS + 273.15); x++)
{
for (double n = ((CELS + 273.15) * (9.0 / 5));
n <= ((CELS + 273.15) * (9.0 / 5)); x++)
{
cout << setw(10) << i << setw(10) << j << setw(10) << k
<< setw(10) << m << setw(10) << n << endl;
}
}
}
}
}
}
And ignore why I have my formulas in the for loop. Formulas were not working using the declared variables so have just done this in the mean time.
You can use some user defined functions to calculate the conversion from Celsius to the other units.
Then you only need one loop:
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::setw;
// define some constant
const double zero_point = 273.15;
constexpr double factor = 9.0 / 5.0;
const double max_cels = 5000;
// farenheit conversion
double cels_to_far( double cels ) {
return cels * factor + 32.0;
}
// kelvin conversion
double cels_to_kel( double cels ) {
return cels + zero_point;
}
// rankine conversion
double cels_to_ran( double cels ) {
return ( cels + zero_point ) * factor;
}
int main()
{
double temp_cels;
double delta_t;
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
while ((temp_cels < -zero_point) || (temp_cels > 5000)) {
cout << "ERROR: out of range.\n";
cout << "Enter the temperature in celsius: ";
cin >> temp_cels;
}
cout << "Enter the increment value: ";
cin >> delta_t;
cout << "\n # Cels Fahr Kel Rank\n";
// output loop
for ( int i = 0; i < 20; ) {
cout << setw(10) << ++i << std::fixed << std::setprecision(2)
<< setw(10) << temp_cels
<< setw(10) << cels_to_far(temp_cels)
<< setw(10) << cels_to_kel(temp_cels)
<< setw(10) << cels_to_ran(temp_cels) << std::endl;
temp_cels += delta_t;
}
}
The output is as expected ( 50° Celsius and increment of 5°):
# Cels Fahr Kel Rank
1 50.00 122.00 323.15 581.67
2 55.00 131.00 328.15 590.67
3 60.00 140.00 333.15 599.67
4 65.00 149.00 338.15 608.67
5 70.00 158.00 343.15 617.67
6 75.00 167.00 348.15 626.67
7 80.00 176.00 353.15 635.67
8 85.00 185.00 358.15 644.67
9 90.00 194.00 363.15 653.67
10 95.00 203.00 368.15 662.67
11 100.00 212.00 373.15 671.67
12 105.00 221.00 378.15 680.67
13 110.00 230.00 383.15 689.67
14 115.00 239.00 388.15 698.67
15 120.00 248.00 393.15 707.67
16 125.00 257.00 398.15 716.67
17 130.00 266.00 403.15 725.67
18 135.00 275.00 408.15 734.67
19 140.00 284.00 413.15 743.67
20 145.00 293.00 418.15 752.67
You need exactly one for loop, incrementing by x. ( The nested for loops are a mistake )
Start with the one, single for loop that you need: the one that counts through the lines of the output table.
In the body of the loop, calculate everything you need for that line, and output it.
Something like this:
for( int line_count = 0;
line_count < 20;
line_count++ )
{
double line_temp_celsius =
start_celsius + line_count * celsius_increment;
// calculate the other values based line_temp_celsius
...
}
The calculation must be in the loop where you change the value of CELS.
There should be a single loop. The result looks like this. See live demo
for (int i = 1; i <= 20; i++, CELS+=x)
{
double FAR = (CELS * (9.0 / 5) + 32); // farenheit conversion
double KEL = (CELS + 273.15); // kelvin conversion
double RANK = ((CELS + 273.15) * (9.0 / 5)); // rankine conversion
cout << setw(10) << i << setw(10) << CELS << setw(10) << FAR
<< setw(10) << KEL << setw(10) << RANK << endl;
}
I have already written most of the code for the problem and it works. I'm just unsure of how to format the output.
Problem : Design and develop a C++ program for Calculating e(n) when delta <= 0.000001
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!
e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!
delta = e(n) – e(n-1)
You do not have any input to the program. Your output should be something like this:
N = 2 e(1) = 2 e(2) = 2.5 delta = 0.5
N = 3 e(2) = 2.5 e(3) = 2.565 delta = 0.065
#include <iostream>
using namespace std;
//3! = 3 * 2!
//2! = 2 * 1!
//1! = 1
int factorial(int number)
{
//if number is <= 1, return 1
if (number <= 1)
{
return 1;
}
// otherwise multiply number by factorial(number - 1)
else
{
//otherwise multiply number by factorial(number - 1) and return it
int temp = number * factorial(number - 1);
cout << "factorial of " << number << " = " << temp << endl;
return temp;
}
}
double sumOfFactorials(int n)
{
double sum = 0;
//loop from 1..n, adding the factorial division to a sum
for (int i = 1; i <= n; i++)
{
double dividedValue = 1.00000 / factorial(i);
cout << fixed;
sum = sum + dividedValue;
}
return sum;
}
/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n)
{
double value = 1 + sumOfFactorials(n);
return value;
}
int main()
{
cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}
You have the right code, All you need is to format the output. Just modify the main() method. here is a snippet you can try.
NOTE : There is an error in the precision of the answer, I think you can correct it.
PS : Please uncomment your debugging cout lines.
int main()
{
for(int i = 2; i<4; i++){
double en_1 = e(i-1);
double en = e(i);
double delta = en - en_1;
cout << "N = "<<i;
cout << " e("<< (i-1) <<") = " << en_1;
cout << " e("<< (i) <<") = " << en;
cout << "delta = " << delta;
cout << "\n";
}
}
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
double cosin_value( double value );
double sin_value( double value );
double big_degree( double value );
double big_radian( double value );
double x;
double value;
double degree;
double radian;
const double PI = 3.14159;
char choice;
char yes;
int main()
{
cout << "Please enter an angle value => ";
cin >> value;
cout << "Is the angle in Degree or Radian?" << endl;
cout << "\t" << "Type D if it is in Degree" << endl;
cout << "\t" << "Type R if it is in Radian" << endl;
cout << "Your response => ";
cin >> choice; //degree or radian?
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
if (choice == 'D' || choice == 'd')
{
big_degree (value);
cout << " " << "sin(x) = " << "\t" << sin_value(degree) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(degree) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(degree) / cosin_value(degree) << endl;
}
else if (choice == 'R' || choice == 'r')
{
big_radian (value);
cout << " " << "sin(x) = " << "\t" << sin_value(radian) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(radian) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(radian) / cosin_value(radian) << endl;
}
return 0;
}
// Sine,cosine functions
// angle -360<value<360
double sin_value( double value )
{
int count=1;
double sine, num, dem, sign, term;
sine = 0;
sign = 1;
num = value;
dem = count;
while ( count <= 20 )
{
term = ( num / dem );
sine = sine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (sine);
}
double cosin_value( double value )
{
int count = 0;
double cosine, num, dem, sign, term;
cosine = 0;
sign = 1;
num = 1;
dem = 1;
while ( count <= 20 )
{
term = ( num / dem );
cosine = cosine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (cosine);
}
double big_degree( double value )
{
int result;
const int angle = 360;
if (value >= 360 || value <= -360)
{
result = value / angle;
degree = ( value - ( result * angle ) ) * PI / 180;
}
else
{
degree = ( value * PI ) / 180;
}
return (degree);
}
double big_radian( double value )
{
int result;
if (value >= 2 * PI || value <= -2 * PI)
{
result = value / ( 2 * PI );
radian = ( value - ( result* 2 * PI ) );
}
else
{
radian = value;
}
return (radian);
}
I have few problems here:
How can the program shows tan(x) is infinity when I input a value 90 degree or 1.5708 radian? When I input 90 degree, it gave me an output of 0.0000013268 instead of 0 for cos(x).
I tried to put in this command in my cosin function where If cos(x)<0.00001, set it to zero, it worked for 90 degree but for other values like 2.3145 radian, cos(x) value is 0 instead of -0.677013.
I appreciate your guides!
Use epsilon value just like you mentioned in question #2.
Use an absolute value of cos(x) like abs(cos(x)) in your if statement. .
You can also represent infinity with double or float. Check this link.
http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
More importantly, you might want to read this article called "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You will notice that each step of your floating point operations will accumulate errors in calculation.