I am learning the basics for programming in C++ and I need to write a program that performs some basic math functions using if/else statements: subtraction, addition, multiplication ect. I don't get any compile or run time errors, but the values that I end up with are always incorrect.
I changed some things around trying to see where I went wrong but what is printed on the screen as far as words go are correct just not the answers. For instance when I scan a - (subtraction sign) as input it will read the difference between x and y is some ridiculously high number.
Anyway, here is my code & any help would be GREATLY appreciated!
/*
* This program performs some basic math calculations
*/
#include <stdio.h>
#include <math.h>
int main() {
int x,y;
float sum = x+ y;
float difference = x-y;
float product = x*y;
float quotient = x/y;
float exponent = x^y;
float modulus = x%y;
char symbol;
printf("What is the value of x?\n");
scanf("%d", &x);
printf("What is the value of y?\n");
scanf("%d", &y);
printf("What is your operator?\n");
scanf(" %c", &symbol);
if (symbol== '+')
printf("The sum of x and y = %f\n", sum);
else if (symbol=='-')
printf("The difference between x and y = %f\n", difference);
else if (symbol=='*')
printf("The product of x and y = %f\n", product);
else if (symbol=='/')
printf("x divided by y = %f\n", quotient);
else if (symbol=='^')
printf("x multiplied exponentially by y = %f\n", exponent);
else if (symbol=='%')
printf("x is this much percent of y =%f\n", modulus);
return 0;
}
Sine this is a C++ application you can define variables as you want. But keep in mind that a program written in C or C++ and for all other languages will be executed top to bottom so when you declare x and y they has no value read from the user. Always trace your codes from top to bottom. Here I declare x and y and read their values from the user first. Then I calculate their different operations. I think most of them except division can be integers again like x and y but I tries to correct your code.
If you want to have exponentiation in C or C++ you have to write your own code.
#include <stdio.h>
#include <math.h>
float power( int x , int y )
{
float ret = 1 ;
for( int i = 1 ; i <= y ; i++ )
ret *= x ;
return ret ;
}
int main() {
int x,y;
printf("What is the value of x?\n");
scanf("%d", &x);
printf("What is the value of y?\n");
scanf("%d", &y);
printf("What is your operator?\n");
scanf(" %c", &symbol);
float sum = (float)x+ y;
float difference = (float)x-y;
float product = (float)x*y;
float quotient = (float)x/y;
//float exponent = (float)x^y; //Exponentiation should be implemented using multiplication and loops.
float exponent = power( x , y ) ;
float modulus = (float)x%y;
char symbol;
if (symbol== '+')
printf("The sum of x and y = %f\n", sum);
else if (symbol=='-')
printf("The difference between x and y = %f\n", difference);
else if (symbol=='*')
printf("The product of x and y = %f\n", product);
else if (symbol=='/')
printf("x divided by y = %f\n", quotient);
else if (symbol=='^')
printf("x multiplied exponentially by y = %f\n", exponent);
else if (symbol=='%')
printf("x is this much percent of y =%f\n", modulus);
return 0;
}
You are performing ALL of the calculations even before you've initialized x and y. Uninitialized variables have indeterminate contents and thus any result you have are indeterminate. You are running the risk of invoking Undefined Behavior with some of your statements (which means that it is impossible to say what your code will do with any amount of certainty). Do your operations only after you've read in the values of x and y.
#include <math.h>
Why do you have this include if you don't use any functions from <math.h>?
float sum = x+ y;
The sum (or difference) of two integers will always be an integer. Why are you using a float here?
float quotient = x/y;
This does integer division and the result is converted to a float. So, the results may not be what you intend. Try to convert any one of the arguments to a float/double in order to get the correct result. Also, you should always check for division by zero. Same goes for your modulus calculation.
float exponent = x^y;
There is no exponentiation operator in C. You need to use a library function (such as pow) or roll your own.
scanf(" %c", &symbol);
Why do you have the space in front?
There is also no need for this huge if-else ladder. Try using a switch.
You need to pick up a good book and start reading to understand how C works.
Related
hey I am making small C++ program to calculate the value of sin(x) till 7 decimal points but when I calculate sin(PI/2) using this program it gives me 0.9999997 rather than 1.0000000 how can I solve this error?
I know of little bit why I'm getting this value as output, question is what should be my approach to solve this logical error?
here is my code for reference
#include <iostream>
#include <iomanip>
#define PI 3.1415926535897932384626433832795
using namespace std;
double sin(double x);
int factorial(int n);
double Pow(double a, int b);
int main()
{
double x = PI / 2;
cout << setprecision(7)<< sin(x);
return 0;
}
double sin(double x)
{
int n = 1; //counter for odd powers.
double Sum = 0; // to store every individual expression.
double t = 1; // temp variable to store individual expression
for ( n = 1; t > 10e-7; Sum += t, n = n + 2)
{
// here i have calculated two terms at a time because addition of two consecutive terms is always less than 1.
t = (Pow(-1.00, n + 1) * Pow(x, (2 * n) - 1) / factorial((2 * n) - 1))
+
(Pow(-1.00, n + 2) * Pow(x, (2 * (n+1)) - 1) / factorial((2 * (n+1)) - 1));
}
return Sum;
}
int factorial(int n)
{
if (n < 2)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
double Pow(double a, int b)
{
if (b == 1)
{
return a;
}
else
{
return a * Pow(a, b - 1);
}
}
sin(PI/2) ... it gives me 0.9999997 rather than 1.0000000
For values outside [-pi/4...+pi/4] the Taylor's sin/cos series converges slowly and suffers from cancelations of terms and overflow of int factorial(int n)**. Stay in the sweet range.
Consider using trig properties sin(x + pi/2) = cos(x), sin(x + pi) = -sin(x), etc. to bring x in to the [-pi/4...+pi/4] range.
Code uses remquo (ref2) to find the remainder and part of quotient.
// Bring x into the -pi/4 ... pi/4 range (i.e. +/- 45 degrees)
// and then call owns own sin/cos function.
double my_wide_range_sin(double x) {
if (x < 0.0) {
return -my_sin(-x);
}
int quo;
double x90 = remquo(fabs(x), pi/2, &quo);
switch (quo % 4) {
case 0:
return sin_sweet_range(x90);
case 1:
return cos_sweet_range(x90);
case 2:
return sin_sweet_range(-x90);
case 3:
return -cos_sweet_range(x90);
}
return 0.0;
}
This implies OP needs to code up a cos() function too.
** Could use long long instead of int to marginally extend the useful range of int factorial(int n) but that only adds a few x. Could use double.
A better approach would not use factorial() at all, but scale each successive term by 1.0/(n * (n+1)) or the like.
I see three bugs:
10e-7 is 10*10^(-7) which seems to be 10 times larger than you want. I think you wanted 1e-7.
Your test t > 10e-7 will become false, and exit the loop, if t is still large but negative. You may want abs(t) > 1e-7.
To get the desired accuracy, you need to get up to n = 7, which has you computing factorial(13), which overflows a 32-bit int. (If using gcc you can catch this with -fsanitize=undefined or -ftrapv.) You can gain some breathing room by using long long int which is at least 64 bits, or int64_t.
I am trying to calculate PI with the infinite series. When I started my programm I excpected to get some wrong nummbers, but instead I get the output "nan".
Does anyone know why?
Here's the code:
#include <iostream>
using namespace std;
int main()
{
long double pi;
float x;
int y = 3;
bool loop = true;
while(true)
{
x=1/y;
y+2;
if(loop == true)
{
pi -= x;
loop = false;
}
else if(loop == false)
{
pi += x;
loop = true;
}
cout<<pi<<" ";
}
return 0;
}
The behaviour of your code is undefined as pi is not initialised when you read its value on adding or subtracting x to or from it. That accounts for the NaN: some compilers helpfully - in some ways - set uninitialised floating point variables to NaN.
x = 1 / y; sets x to 0 due to integer division. Did you want 1.0 / y?
y + 2; is a no-op. Did you want y += 2?
Note that you need to multiply the series by 4 to obtain pi, and this series converges especially slowly, some 300 terms are needed for two decimal places. And your starting value of y is wrong. Shouldn't it be 1?
Hello I am solving trigonometry functions like sin(x) and cos(x) with Taylor Series Expansions
Problem: My values are not wrong just not very precise
My question is whether I can improve the accuracy of these functions, I think I have tried everything but I need your suggestions.
double trig::funcsin(int value)
{
sum = 0;
//summation
factorial fac;
for(int i = 0; i < 7; i++)
{
sum += pow((-1), i)*(((double)pow(value, (double)2*i+1)/(double)fac.fact((double)2*i+ 1)));
}
return sum;
}
double trig::funccos(int value)
{
factorial fac;
sum = 0;
for(int i = 0;i < 7;i++)
{
sum += (pow((-1), i)*((double)pow(value, (double)2*i)/(double)fac.fact((double)2*i)));
}
return sum;
}
Example:
Real: -0.7568024953
Mine: -0.73207
Real: -0.27941549819
Mine: -0.501801
Aslo as x becomes larger the output values become less precise at an exponential rate.
I am on GCC compiler, please give me suggestions
The following code demonstrates the Taylor series (about x==0) for the sin() function.
As you know, the sine function repeats an identical cycle for every 2*pi interval.
But the Taylor series is just a polynomial -- it needs a lot of terms to approximate a wiggly function like sine. And trying to approximate the sine function at some point far away from the origin will require so many terms that accumulated errors will give an unsatisfactory result.
To avoid this problem, my function starts by remapping x into a single cycle's range centered around zero, between -pi and +pi.
It's best to avoid using pow and factorial functions if you can instead cheaply update components at each step in the summation. For example, I keep a running value for pow(x, 2*n+1): It starts off set to x (at n==0), then every time n is incremented, I multiply this by x*x. So it only costs a single multiplication to update this value at each step. A similar optimization is used for the factorial term.
This series alternates between positive and negative terms, so to avoid the hassle of keeping track of whether we need to add or subtract a term, the loop handles two terms on each iteration -- it adds the first and subtracts the second.
Each time a new sum is calculated, it is compared with the previous sum. If the two are equal (indicating the updates have surpassed the sum variable's precision), the function returns. This isn't a great way to test for a terminating condition, but it makes the function simpler.
#include <iostream>
#include <iomanip>
double mod_pi(double x) {
static const double two_pi = 3.14159265358979 * 2;
const int q = static_cast<int>(x / two_pi + 0.5);
return x - two_pi * q;
}
double func_sin(double x) {
x = mod_pi(x);
double sum = 0;
double a = 1; // 2*n+1 [1, 3, 5, 7, ...]
double b = x; // x^a
double c = 1; // (2*n+1)!
const double x_sq = x * x;
for(;;) {
const double tp = b / c;
// update for negative term
c *= (a+1) * (a+2);
a += 2;
b *= x_sq;
const double tn = b / c;
const double ns = tp - tn + sum;
if(ns == sum) return ns;
sum = ns;
// update for positive term (at top of loop)
c *= (a+1) * (a+2);
a += 2;
b *= x_sq;
}
}
int main() {
const double y = func_sin(-0.858407346398077);
std::cout << std::setprecision(13) << y << std::endl;
}
What this code does now: I give int values and it calculates the average between them.
What Ive spent hours on trying to get it do: Ive tried making it so that it would calculate the average between double values. Ive tried everything but it always fails or goes into an infinite loop or will not compile.
Question: So how should I modify my code to make it work with double values/numbers?
#include <stdio.h>
void main()
{
int Tau[10]={0,0,0,0,0,0,0,0,0,0};
int r, i = 0;
int m = 0;
int huku = 0;
do{
printf("Enter numbers: ");
scanf_s("%d", &i);
Tau[m]+=i;
huku++;
}while(i != 0);
r = (Tau[m]/(huku-1));
printf("The average of your numbers is; %d\n", r);
}
You have some issues in your code but basically, integer division will not give you doubles. The result of an integer divided by an integer is another integer, not a double. If you want doubles you need to cast either the numerator or denominator to a double and store the result in a double.
Welcome to Numerical Analysis 1001.
Integer math:
2 / 3 = 0;
4 / 2 = 2;
5 / 2 = 2;
Integers don't do fractions.
I don't see why you need Tau to be a vector in your case. An int would suffice.
huku-1 -> That is wrong. It should be just huku.
You need to cast Tau and huku to double when you divide. It won't hurt to check that huku is != 0 also.
m is useless. Just delete it.
r shouldn't be an int if you wish to store Tau/huku in it.
in printf replace %d with %lf
The simplest changes only involve four lines:
double Tau[10] = {0,0,0,0,0,0,0,0,0,0};
double r, i = 0;
scanf_s("%f", &i);
printf("The average of your numbers is; %f\n", r);
Note that this doesn't address the coding issues; all it does is change the code to read and work with double instead of int.
double r = 0;
int i = 0;
r = ((double)Tau[m]/((double)huku-1));
printf("The average of your numbers is; %f\n", r);
// Question is tagged for C++, but the code is in C.
// I will change your code a bit, because you had quite a few mistakes.
#include <stdio.h>
void main ()
{
int sum = 0; // sum of all numbers you entered, to find average you only need total sum and number of entries
int numOfEntries; // number of entries (numbers taken from input)
int inputNum; // variable where you will write numbers from input one by one
double average; // Not really needed, but it can help to simplify the problem to you.
printf("Enter numbers: ");
do
{
scanf_s("%d", &inputNum);
sum += inputNum;
numOfEntries++;
} while (inputNum != 0); // I understand you read numbers until you read value 0.
// int / int will give you rounded number, not the true average, so we need to convert one of the operands to a real number, in this case double
// double / int or int / double will give you a real number as result, which will have true average value, and that is why I converted sum to a real number
if (numOfEntries != 0)
average = (double)sum / numOfEntries;
else
average = 0;
printf("The average of your numbers is; %f\n", average); // Here I did it again - print double instead of int to get true value.
}
It will be even easier to change this:
....
double sum = 0;
...
average = sum / numOfEntries; // Here sum is already double, not int, so you don't need to change it manually.
...
Now, if you want to make it work for double, the only difference will be:
double sum = 0;
double inputNum;
scanf_s("%lf", &inputNum);
average = sum / numOfEntries;
So, to round up the story - you have variable to input a number from keyboard, a variable which holds sum of all entered numbers so far, a variable which counts how many numbers you entered from keyboard. You input numbers until you enter 0 as value, then the program will exit the loop. Formula for average number is sum of all divided by number of numbers. With integers you have to add conversion to a real number or otherways you won't get accurate result.
I hope I didn't confuse you. :D
#include <stdio.h>
void main(void)
{
int a;
int result;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &a);
for( int i = 1; i <= 4; i++ )
{
result = a ^ i;
sum += result;
}
printf("%d\n", sum);
}
Why is ^ not working as the power operator?
Well, first off, the ^ operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.
Now, regarding your problem with using the pow() function, some googling shows that casting one of the arguments to double helps:
result = (int) pow((double) a,i);
Note that I also cast the result to int as all pow() overloads return double, not int. I don't have a MS compiler available so I couldn't check the code above, though.
Since C99, there are also float and long double functions called powf and powl respectively, if that is of any help.
In C ^ is the bitwise XOR:
0101 ^ 1100 = 1001 // in binary
There's no operator for power, you'll need to use pow function from math.h (or some other similar function):
result = pow( a, i );
pow() doesn't work with int, hence the error "error C2668:'pow': ambiguous call to overloaded function"
http://www.cplusplus.com/reference/clibrary/cmath/pow/
Write your own power function for ints:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
First of all ^ is a Bitwise XOR operator not power operator.
You can use other things to find power of any number. You can use for loop to find power of any number
Here is a program to find x^y i.e. xy
double i, x, y, pow;
x = 2;
y = 5;
pow = 1;
for(i=1; i<=y; i++)
{
pow = pow * x;
}
printf("2^5 = %lf", pow);
You can also simply use pow() function to find power of any number
double power, x, y;
x = 2;
y = 5;
power = pow(x, y); /* include math.h header file */
printf("2^5 = %lf", power);
include math.h and compile with gcc test.c -lm
It's not working because c as well as c++ do not have any operators to perform power operations.
What you can do is, you can use math.h library and use pow function. There is a Function for this instead of the operator.
` #include<stdio.h>
#include<math.h>
int main(){
int base = 3;
int power = 5;
pow(double(base), double(power));
return 0;
}`
You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.
There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number.
Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.
1. Using a while loop.
#include <stdio.h>
int main() {
int base, expo;
long long result = 1;
printf("Enter a base no.: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &expo);
while (expo != 0) {
result *= base;
--expo;
}
printf("Answer = %lld", result);
return 0;
}
2. Using the pow() function
#include <math.h>
#include <stdio.h>
int main() {
double base, exp, result;
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent: ");
scanf("%lf", &exp);
// calculate the power of our input numbers
result = pow(base, exp);
printf("%.1lf^%.1lf = %.2lf", base, exp, result);
return 0;
}
If you are trying to calculate the power of base 2, you can use the bitwise shift operator to calculate the power. For example, say you wanted to calculate 2 to the power of 8.
2 << 7
For integer exponent, you may simply write your implementation of pow()
int myPow(int x, int n)
{
if (n == 0) return 1;
return x * myPow(x, n - 1);
}
All the solutions here, except for the ones that use math.h
will not work for fractional powers.
The last example here is by far the worst and acctually copy'n'paste.
It is not only slow but it will break stuff at some point.
Just use the math.h with pow() as already stated and that's good enough.
If you are not allowed to use math.h, use a tail-recursive function, that saves the current operation result in an accumulator and returns the accumulator at the end, thus avoiding exploding function calls due to extensive traces.