So this is my code
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int kol=0, x;
cout << "Insert a number: ";
cin >> x;
while (x > 0);
{
div_t output;
output = x;
x = div(output, 10);
kol += kol;
}
cout << "Amount: " << kol << endl;
system ("pause");
return 0;
}
And I got this error:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversation)
Can someone tell me what I did wrong, and how to fix?
You are treating div_t like an int; it isn't one. It's a struct.
See http://en.cppreference.com/w/cpp/numeric/math/div
Can you expound on what you are trying to do? Clearly, there's repetitive division intended, but that's all I surmise.
output is a div_t. x is an int, so output = x is like trying to assign an apple to an orange. You can't do it without establishing a set of rules for turning the apple into an orange.
We could try to write such a rule, but why bother? Instead let's look at the code that got us into this predicament and try to figure out the context.
while (x > 0);
{
div_t output;
output = x;
x = div(output, 10);
kol += kol;
}
The purpose of this loop seems to be to count of the number of times x was divided by ten and store the count in kol.
div_t is the result of a call to div, so assigning a value to the result before performing the operation that will generate the result is a touch unusual. Perhaps OP meant
while (x > 0);
{
div_t output;
output = div(x, 10);
kol += kol;
}
to divide x by ten and get the quotient and remainder.
But this loop will never exit because x is never changed. If it is not zero, the loop will never terminate and if it is zero the loop will never enter. Perhaps
while (x > 0);
{
div_t output;
output = div(x, 10);
x = output.quot;
kol += kol;
}
would be more appropriate. The remainder is never used however, so div is effectively wasted and
while (x > 0);
{
x = x / 10; // or x /= 10;
kol += kol;
}
would provide the same result with far less fuss.
Related
I want to find the sum up to the 'n'th term for the following series:
(1/2)+((1*3)/(2*4))+((1*3*5)/(2*4*6))....
So, I wrote the following program in c++ :
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
int main()
{
int p=1, k=1, n=0;
float h=0;
cout<<"Enter the term: ";
cin>>n;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
p*=((2*j)-1);
k*=(2*j);
}
h+=(p/k);
p=1;
k=1;
}
cout<<"The sum is : "<<h;
return 0;
getch();
}
However, the output of the program always gives me '0'. I can't figure out the problem with the program.
N.B. I'm new to programming.
The problem here is that you haven't declared p and k as float or doubleor explicitly cast them as such before the calculation and assignment to h.
What's happening is for every iteration of the loop p < k (by nature of the problem) since p and k are both declared as int, p / k = 0. So you're just summing 0 for every iteration.
Either declare p and k as float or double or do this:
h += ((float) p) / ((float) k)
Also, for this specific problem I assume you're looking for precision, so be wary and look into that as well Should I use double or float?
implicit conversion and type casting are a trap where all newbies fall.
in the instruction:
h += p/k;
the compiler performs an integer division first, then a promotion of the result to floating point type.
and since:
p < k ; for all i,j < n
then:
res = (p / k) < 1 => truncates to 0; // by integer division
thus:
sum(1->n) of p/k = sum (1->n) 0 = 0;
finally:
h = conversion to float of (0) = 0.0f;
that's why you have the result of 0.0f at the end.
the solution:
1- first of all you need to use the natural type for floating point of c++ which is "double" (under the hood c++ promotes float to double, so use it directly).
2- declare all your variable as double, except the number of terms n:
3- the number of terms is never negative, you need to express that in your code by declaring it as an unsigned int.
4- if you do step 3, make sure to catch overflow errors, that is if the user enters a negative number your risk to have a very big number in "n", expel : n =-1 converts to 0xffffffff positive number.
5- engineer your code sometimes is better.
6- include only the headers that you need, and avoid a importing any namespace in your global namespace.
here is how i think you should write your program.
#include <iostream>
double sum_serie(unsigned int n)
{
double prod = 1.0, sum = 0.0;
for (double c=1; c<=n ; c++)
{
prod *= ( ( 2*c ) - 1 ) / ( 2*c ); // remark the parenthesis
sum += prod;
}
return sum;
}
int main()
{
unsigned int n = 0;
int temp = 0;
std::cout << " enter the number of terms n: ";
std::cin >> temp;
if (temp > 0)
n = temp; // this is how you catch overflow
else
{
std::cout << " n < 0, no result calculated " << std::endl;
return 0;
}
std::cout << " the result is sum = " << sum_serie(n) << std::endl;
return 0;
}
I know that the question was about the implicit conversion and casting in C++, but even the way of writing a code can show you what bugs you have in it, so try to learn a proper way of expressing your ideas into code, debugging comes natural afterward.
Good Luck
Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)
Im not very good at this yet and I'm trying to learn how to get user declared variables to work within my equations.
For now I just want the computer to spit out a randomized multiplication based on a maximum number specified by the user.
When I try to run this the machine spits back these errors:
12:16: error: ambiguous overload for 'operator>>' in 'std::cin >> 32767'
14:61: error: 'x' was not declared in this scope
14:64: error: 'y' was not declared in this scope
15:16: error: statement cannot resolve address of overloaded function
20:9: error: declaration of 'int x' shadows a parameter
21:5: error: expected ',' or ';' before 'int
The eventual goal is that the computer will generate the problem within the difficulty parameter then remove one of the variables in the equation to quiz the user.
#include <cstdlib>
#include <iostream>
using namespace std;
int mult( int x, int y );
int main()
{
cout <<"Please enter a number between 2 and 21, this will determine how difficult your problems are.";
cin >> RAND_MAX;
cin.ignore();
cout << "The product of your numbers is:" << mult ( x, y ) <<"\n";
cin.get;
}
int mult (int x, int y)
{
int x = rand()
int y = rand()
return x * y;
}
There are quite a few errors here. I'll try and be kind.
You need semi-colons after both of your rand() calls.
x and y are not declared anywhere in main(). I don't know why you're passing them as parameters to mult(), but I assume there will be some related functionality down the line.
RAND_MAX is a constant, so cin >> RAND_MAX makes no sense. Instead, see #Bill's answer.
You need parens after cin.get.
Here's a working example, hopefully this is what you want it to do:
#include <cstdlib>
#include <iostream>
using namespace std;
int mult( int x, int y, int randMax );
int main()
{
int x = 0,
y = 0,
randMax;
cout <<"Please enter a number between 2 and 21, this will determine how difficult your problems are.";
cin >> randMax;
cin.ignore();
cout << "The product of your numbers is:" << mult ( x, y, randMax ) <<"\n";
cin.get();
}
int mult (int x, int y, int randMax)
{
x = rand() % randMax;
y = rand() % randMax;
return x * y;
}
Others have pointed out problems such as trying to modify RAND_MAX, expecting that to change how rand() operates. I just want to show how to use the modern <random> library in place of rand().
There are a number of reasons not to use rand().
The reason which is most significant to your case is that it's not straightforward to use it to correctly get values in the range you want. The most common way people do it is something like rand() % randMax + 1, but for most values of randMax this will actually produce some numbers in the range [1,randMax] more often than other numbers. If it's important to get evenly distributed numbers then you need something more like:
int v;
do {
v = rand();
} while (v >= RAND_MAX / randMax * randMax);
v = v % randMax + 1;
which isn't so simple. <random> provides many pre-made distributions so you often don't have to write your own like this.
Other reasons not to use rand() are that it's not thread safe or easy to use in a multithreaded program, and that usually it's not very random. <random> can be used to fix these problems as well.
Here's a version of your program using <random>.
#include <random>
#include <iostream>
// global random number engine and distribution to use in place of rand()
std::default_random_engine engine;
std::uniform_int_distribution<> distribution;
int mult()
{
int x = distribution(engine);
int y = distribution(engine);
return x * y;
}
int main()
{
std::cout << "Please enter a number between 2 and 21, this will determine how difficult your problems are.";
int max;
std::cin >> max;
// set the global distribution based on max
distribution.param(std::uniform_int_distribution<>(1,max).param());
std::cout << "The product of your numbers is:" << mult() << "\n";
}
I am having the hardest time figuring out what is wrong here:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double fact(double);
double sinTaylor(double);
double cosTaylor(double);
int main()
{
double number, sineOfnumber, cosineOfnumber;
cout << "Enter a number, then I will calculate the sine and cosine of this number" << endl;
cin >> number;
sineOfnumber = sinTaylor(number);
cosineOfnumber = cosTaylor(number);
cout << fixed << endl;
cout << cosineOfnumber << endl;
cout << sineOfnumber << endl;
return 0;
}
double fact(double n)
{
double product = 1;
while(n > 1)
product *= n--;
return product;
}
double sinTaylor(double x)
{
double currentIteration, sumSine;
for(double n = 0; n < 5; n++)
{
currentIteration = pow(-1, n)*pow(x, 2*n+1) / fact(2*n+1);
sumSine += currentIteration;
}
return sumSine;
}
double cosTaylor(double y)
{
double currentIteration, sumCosine;
for(double n = 0; n < 5; n++)
{
double currentIteration = pow(-1, n)*pow(y, 2*n) / fact(2*n);
sumCosine += currentIteration;
}
return sumCosine;
}
Ok, so here's my code. I'm pretty content with it. Except for one thing:
sineOfnumber and cosOfnumber, after the calling of sinTaylor and cosTaylor, will add each other in the following cout line that will print each other.
In other words, if number is equal to lets say, .7853, 1.14 will be printed in the line that is intended to print cosineOfnumber, and sineOfnumber will print the result normally.
Can anyone help me identify why this is? Thank you so much!
Are you ever initializing the variables sumSine and sumCosine in your functions? They're not guaranteed to start at zero, so when you call += inside your loop you could be adding computed values to garbage.
Try initializing those two variables to zero and see what happens, as other than that the code seems okay.
The series for the sine is (sorry for the LaTeX):
sin(x) = \sum_{n \ge 0} \frac{x^{2 n + 1}}{(2 n + 1)!}
If you look, given term t_{2 n + 1} you can compute term t_{2 n + 3} as
t_{2 n + 3} = t_{2 n + 1} * \frac{x^2}{(2 n + 2)(2 n + 3)}
So, given a term you can compute the next one easily. If you look at the series for the cosine, it is similar. The resulting program is more efficient (no recomputing factorials) and might be more precise. When adding up floating point numbers, it is more precise to add them from smallest to largest, but I doubt that will make a difference here.
I have the following problem : I write my code with the Qt IDE. I was informed that when people try to compile it with other IDE's (like codeblocks, or visual studio) The output they get is different and that there are maufunctions. Any ideas what can be causing this ? I will give you an example:
This is Newton's Method with a function who's root is 2.83something. I get the same, correct calulations each time I run it in Qt. I get "nan" in code blocks and something irrelevant as well in visual studio. I don't understand, do I have a mistake somewhere in my code ? What can be causing this ?
#include <iostream>
#include <cmath> // we need the abs() function for this program
using namespace std;
const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style
double newton_theorem(double x)
{
double old_x = x; // asign the value of the previous iteration
double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation
double f_x2 = 2 * old_x; // create the bottom side
double new_x = old_x - f_x1 / f_x2; // calculate f(x[n+1])
//cout << new_x << endl; // remove the // from this line to see the result after each iteration
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
newton_theorem(new_x);
}
}// newton_theorem
int main()
{
cout << "This program will find the root of the function f(x) = x * x - 8" << endl;
cout << "Please enter the value of X : ";
double x;
cin >> x;
double root = newton_theorem(x);
cout << "The approximate root of the function is: " << root << endl;
return 0;
}//main
Yes, you run into undefined behavior:
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
/*return*/ newton_theorem(new_x); // <<--- HERE!
}
Missing a return on the else branch.
We could try to explain why Qt works (its compiler automatically puts the result of newton_theorem in the return registry, or shares registries, or whatever), but the fact of the matter is anything can happen. Some compilers might behave the same on subsequent runs, some might crash all the time.