Product sequence in a for cicle [duplicate] - c++

This question already has an answer here:
Integer division always zero [duplicate]
(1 answer)
Closed 8 years ago.
I know this has to be something extremely idiotic, but I really can't find my mistake.
I'm trying to write a program to calculate (2/i)^i, where i is an integer put in input by the user. If i = 0, the function returns 1.
This is the function I have been using.
double f (int x)
{
double y = 1.0;
if (x == 0)
return 1;
else
for (int i = 1; i <= x; i++)
y *= pow (2/i, i);
return y;
}
int main ()
{
for(int i=0;i<=10;++i)
cout << "f(" << i << ") =" << f(i) << endl;
}
Now.. This is supposed to be an extremely simple code. Yet, it doesn't work. It compiles correctly, but the results are not what I'm expecting. After some iterations, I always get 0 as a result. What am I doing wrong?

Integer division:
change to:
y *= pow (2.0/i, i);
^^^
Also, why do you need a loop?

Related

How to detect integer overflow? [duplicate]

This question already has answers here:
How to detect integer overflow in C [duplicate]
(3 answers)
Closed 1 year ago.
Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read
the values into a vector, then calculate the sum of the first N
values. For example: “Please enter the number of values you want to
sum:” 3 “Please enter some integers (press '|' to stop):” 12 23 13 24
15 | “The sum of the first 3 numbers ( 12 23 13 ) is 48.” Handle all
inputs. For example, make sure to give an error message if the user
asks for a sum of more numbers than there are in the vector.
Modify the program from exercise 8 to write out an error if the result cannot be represented as an int.
So in exercise 9 it says to write out an error message if the result cannot be represented as an int, but if I'm only adding up integers here the only thing I can think of here that would cause a number to not be able to be represented as an int would be if there's some integer overflow and the integer goes above INT_MAX or below INT_MIN but how exactly can I detect this?
This is my code:
#include<vector>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<stdexcept>
using namespace std;
int main()
{
int N = 0;
vector<int> values;
cout << "Please enter the number of values you want to sum." << '\n';
cin >> N;
cout << "Please enter some numbers" << '\n';
for (int tempnum; cin >> tempnum; )
{
values.push_back(tempnum);
}
if (N > values.size())
{
cout << "How am I gonna add up more numbers than you gave me?" << '\n';
}
else
{
int total = 0;
for (int i = 0; i < N; i++)
{
total += values[i];
}
}
}
But I can't just check if total is above or below INT_MAX or INT_MIN because INT_MAX +1 or something returns some random negative value so I'm not really sure how to do this
You can do this with some arithmetic:
So you want to know if acc + x > INT_MAX, where acc is the accumulator (the sum so far) and x is the next element. Adding them together may overflow though. But acc > INT_MAX - x is equivalent and x is already stored in an int. So this can also not underflow, bc. x can be at most INT_MAX.
I.e., just transform the inequation to avoid overflow. In this case, subtract x from both sides.
That only works for positive x though, thanks to user interjay for pointing this out.
With negative x, this becomes a subtraction:
acc + (-x) > INT_MAX
acc - x > INT_MAX
This can not overflow, because we are subtracting from acc. But it may underflow, so the question becomes:
acc - x < INT_MIN
acc < INT_MIN + x
So:
int acc = 0;
for (int i = 0; i < N; ++i) {
int x = values[i];
if (x >= 0 && acc > (INT_MAX - x)) {
cout << "ERROR: Overflow.";
return 1;
} else if (x < 0 && acc < (INT_MIN - x)) {
cout << "ERROR: Underflow.";
return 1;
} else {
acc += x;
}
}

Incorrect mathematical results calculating power series [closed]

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 2 years ago.
Improve this question
#include <iostream>
#include <cmath>
using namespace std ;
int main ()
{
int n, sum=0 ;
cout<< "Input number of terms: " ;
cin>> n ;
for (int i=1; i<=n; i++)
{
int k = pow(10, i) - 1 ;
cout << k ;
if(i < n)
{
cout<< " + " ;
}
sum += k ;
}
cout << "\nThe sum of the series = " << sum ;
{int m;cin>>m;}
return 0 ;
}
every time I run this code it gives me weird output like
9 + 98 + 999 + 9998 + ...
it subtracts some Ks from 2 !!
The rule is mathematically right and there is no syntax errors.
Is it the way of declaring k inside the loop or it's an compiler error ?
So, what's wrong here?
Here is the for loop without using the pow function:
int power = 10;
for (int i = 1; i < n-1; ++i)
{
const int k = power - 1 ;
cout << k;
if(i < n)
{
cout<< " + " ;
}
sum += k;
power *= 10; // This is important.
}
This should be more accurate than using pow because there is no conversions between integer and floating point.
Also, you may want to try using the series from 0 .. (n-1).
I think the best thing to do is to create your own power function because pow() is not working that way before when I used it. Kinda like this one
int pow_num(int base_num, int exp_num)
{
int result = 1;
for(int i = 0; exp_num > i; ++i)
{
result = result * base_num;
}
return (result);
}

c++: general q about for-statements and arguments [duplicate]

This question already has answers here:
What is the correct way of using C++11's range-based for?
(4 answers)
Closed 4 years ago.
I'm in the process of learning c++. I've come across an assignment about temperatures I don't understand. Could you guys clarify some things for me?
Here's the code
// compute mean and median temperatures
int main()
{
vector<double> temps; // temperatures
for (double temp; cin>>temp; ) // read into temp
temps.push_back(temp); // put temp into vector
**// compute mean temperature:
double sum = 0;
for (int x : temps) sum += x;
cout << "Average temperature: " << sum/temps.size() << '\n';**
// compute median temperature:
sort(temps); // sort temperatures
cout << "Median temperature: " << temps[temps.size()/2] << '\n';
}
Now the second block (//compute mean temperature) is the stuff I cannot follow.
First off, a for-statement is used with a single argument. Won't this mean that there is just an initial expression and no condition?
I also don't think I have a firm understanding of int X : temps int X isn't defined anywhere else in this bit of code. Won't it cause an error as it has no value assigned to it? Let's say it has a value of 1; what does it do/what does it check? Does it check how many times X fits in vector temps? Why not do this then:
int sum_of_measurements = 0; //value of all measurements
for (int y = 0; y <= temps.size(); ++y){
sum_of_measurements = sum_of_measurements + temps[y]; // add value of measurement to the total for each measurement
}
double mean = sum_of_measurements/temps.size();
cout << mean <<'\n';
//rest of code
What's this identifier called so I can learn more about it (the : in int X : temps)
Thanks :)
That's the range-based for loop, introduced in C++11.
A statement like:
for (int someVal: someCollection)
will iterate over someCollection with someVal being set to each item within the collection (one per iteration).
In your specific case (after changing the type of x to one more suitable), the snippet:
double sum = 0;
for (double x : temps)
sum += x;
is functionally equivalent to:
double sum = 0;
for (int i = 0; i < temps.size(); ++i)
sum += temps[i];

Can someone explain why a value gets incremented when "++" is used for comparison? [duplicate]

This question already has answers here:
How does the increment operator work in an if statement?
(7 answers)
Closed 4 years ago.
This may already be a question out there, but with the lack of specific key terms, it's a bit hard to search for. Just looking for more insight on this topic.
Right now, I'm working in C++ and wondering why my value is replaced with an incremented value when I compare using "++".
So here, we print 14 times (numbers 1-14).
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i++) break;
cout << i << endl;
}
Here, we print 30 zeros.
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i+1) break;
cout << i << endl;
}
And this just plain doesn't work. (I wanted to try because i++ = i=i+1).
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < i=i+1) break;
cout << i << endl;
}
Expression i++ has both a value and a side effect. The value is that of i, and the side effect is that i is incremented (after having taken its value as expression result).
Expression i+1, in contrast, does not have a side effect, it only has a value (which is the value of i plus 1) but leaves the value of i as it is.
That's why.
And this just plain doesn't work. (I wanted to try because i++ =
i=i+1).
The reason it doesn't work is because of operator precedence in this expression:
if (13 < i=i+1) break;
It is evaluated by compiler as
if ((13 < i)=(i+1)) break;
and assignment to bool fails. What you need is to add correct parentheses for it to work:
int i = 0, x = 0;
while (x < 30) {
x++;
if (13 < (i=i+1)) break;
cout << i << endl;
}
https://ideone.com/0NSNwU
1
2
3
4
5
6
7
8
9
10
11
12
13

C++ double value losing precision when multiplied?

I am trying to create a function to find the square root of a number. For debugging purposes, it has instructions to print current variable values. The function squareRoot accepts two arguments, x and t. It then declares and initializes n and s. n is the amount to add or subtract, halving every time it is used. s is what is thought to be the current square root. When running, I can clearly see that n is adjusting correctly. However, s stops changing when the first four digits are correct. I am using this call in main():
cout << squareRoot(1000, 10) << "\n";
This should print the square root of 1000 to the nearest tenth, but two weird things happen:
It doesn't stop at 31.6.
It stops at 4 digits!
My theory as to why it stops at four digits is this: In multiplying, s loses some of its precision. Is this true? If so, can you tell me how to correct it? If not, what is causing this and how can I correct that?
I tried to solve it already by using another variable, s1, which would be multiplied and checked. Then s would be incremented by n, and s1 synchronized with s. This didn't work, so I went back to the original code.
My code is as follows:
#include <iostream>
using namespace std;
double squareRoot(double x, int t) {
double s = 0;
double n = 0.1;
while ((s*s) <= x) {
s += n;
n *= 2;
cout << n << "\n" << s << "\n";
}
cout << "\n";
s -= n;
// Keep changing until margin of error is reached
while ((((s*s) - x) < (1/t)) || ((x - (s*s) < (1/t)))) {
// If too high, lower s
if ((s*s) <= x) {
s += n;
n /= 2;
cout << "Adding 1/2 of previous n\n";
}
// If too low, raise s
else if ((s*s) >= x) {
s -= n;
n /= 2;
cout << "Subtracting 1/2 of previous n\n";
}
cout << s << "\n" << n << "\n\n";
}
return s;
}
I am running Windows 7 64 bit, MSVC++ 2008 Express. Thank you in advance for all answers!
It converges to the correct square root, but cout only prints six significant digits by default: 31.xxxx.
Also notice that your termination check does not work because (1/t) will always evaluate to 0 for t>1. Use 1./t instead.
Unrelated, but your sqrt algorithm can be sped up by using an existing one, such as Newton's Method.
It goes like this:
double mySqrt(double x, unsigned long accuracy = 10)
{
if(x < 0.0)
return(-1.0);
double retval = 1.0;
for(unsigned long rep = 0; rep < accuracy; rep++)
retval = ((x / retval) + retval) / 2.0;
return(retval);
}
Newton's method also works for cube roots, etc.
For decimal exponents, look up the Binomial Theorem.
The reason loop isn't stopping is that loop condition isn't correct. You have
while ((current - target < precision) || (target - current < precision)) {
...
}
But either value current - target or value target - current will be <= 0. And 0 < precision. Thus you have equivalent of while (true) {...} loop.
You need something like
while (abs(current - target) > precision) {
...
}
(don't know exact function for getting absolute value in C++)
edit
Just noticed, hamster3null wrote about 1/t before me.