I am learning C++ language, but much confused about a little thing, that is
below I have putted some code of making a square of an integer. But I am not understanding the treatment of x in raiseToPow function. Here double x is an argument taking the value from calling function and passing to x in for loop. So how it makes square of that integer passing from x. Please guide me.
#include <iostream>
using namespace std;
double raiseToPow(double x, int power){
double result;
result = 1.0;
for (int i = 1; i <= power; i++)
{
result *= x;
}
return (result);
}
main()
{
double x;
int i;
cout << "Enter the Number: ";
cin >> x;
cout << "Enter the Power: ";
cin >> i;
cout << x << "Raise to power " << i << " is equal to " << raiseToPow(x , i);
}
double x is the base of the exponentiation xpower.
The function uses the definition xpower is 1 multiplied by x power times. Thus 23 is 1*2*2*2 and 45 is 1*4*4*4*4*4. So double result is set to be 1, then the for loop executes power times, each time multiplying result by x and storing that back in result.
Even though this is C++, not C, the logic is the same.
You pass in a number(x) and its exponent(power). The value of x is multiplied 'power' times.
For example, if you want to know the value of 2 raised to the power of 3, you would pass 2, 3 to the function raiseToPow
The statement
result*=x
is the same as
result = x*result.
So, the first time through the loop, result would just be the value of x (2, in this example). The second time through the loop, result*=x would multiply the value of x(which is 2) times the value stored in result (which, for now, is also 2). The third and final time through the loop, result *=x would multiply x times the value stored in result (which now is 4).
The value of 2^3=8, and that is what the value stored in the variable result is, so the value 8 is returned from the call raiseToPow(2,3).
Related
I'm beginner in using functions, and I wrote this simple code. But I don't know why the volume is always calculated as zero.
#include <iostream>
using namespace std;
double area (double) ;
double volume (double) ;
int main () {
double radious ;
cout << "please enter the Radious \n" ;
cin >> radious ;
cout << "The area = " << area(radious) << "\n" ;
cin >> radious ;
cout << "The volume = " << volume(radious) << "\n" ;
cout << radious << "\n" ;
}
// defintion function of the area
double area (double R) {
return ( (4) * (3.14) * (R * R) ) ;
}
// defintion function of the volume
double volume (double R) {
return ( (3/4) * (3.14) * (R * R * R) ) ;
}
Your function volume will always return zero because 3 divided by 4 is 0 when interpreted as an integer. This is because casting any real value to integer will simply result in discarding decimal part. For example, 2.7 as int will be 2 not 3, there is no rounding, in a mathematical sense.
You can fix this in 2 ways:
A) reorder your equation so division will be the last operation you do, e.g. ((3.14*R*R*R*3)/4). Note that this is often necessary, when you want your result to be int, which is not the case here.
B) explicitly say that either (or both) 3 or 4 have to be treated as a real number (float/double) by adding .0, e.g. 3.0/4 or 3/4.0 or 3.0/4.0. This approach is better in your case since you expect double anyway.
For more information refer to Numeric conversions and this FAQ
The part 3/4 in your code performs an integer division. Integers cannot have floating points so usually the last part of integer is truncated, which leaves 0 in your case.
You can replace 3/4 with 3.0/4.0to make it work.
Good Luck!
I am new to coding and my task is to make the variable 'sum' greater than (not equal to) m by summing up 1/n for an increasing 'n'.
I need to solve the same problem twice (one using a for-loop and once using a while-loop). But both ways end in an infinte loop.
My code is working fine when I replace the "<=" with "<". But that
Can someone help me?
#include <iostream>
using namespace std;
int main () {
unsigned int m = 1;
double sum = 0;
long n;
n = 1;
while (sum <= m) //THIS LINE
{
double sumsum = 1/n;
sum += sumsum;
n++;
}
cout << "n = " << n << endl ;
cout << "sum = " << sum << endl ;
return 0;
}
Epression 1/n with n being of type long and having a value > 1 will always yield 0, since you operate with integral types. Hence, sum will be assigned 1 in the first run, but will never come to a value > 1, as forth on always 0 is added.
Change your code to
double sumsum = 1.0/n;
and it should work. Note that 1.0 enforces to operate with floating points.
So in this program i am trying to print out the standard deviation of a set of numbers the user enters in. The formula to calculate standard deviation is correct (or as correct as it needs to be) so that is not the problem, but when i run the program everything goes well until the console prints out the results. It prints that totalStandardDeviation = nan
what exactly does than mean? is nan the same as nil? has it lost the value somehow and not been able to find it? thanks for any help you may provide.
#include <iostream>
#include <cmath>
using namespace std;
double returnStandardDeviation(double x, int counter);
double total;
int userInput = 1;
int counter = 0;
double x;
double x1;
double x2;
double standardDeviation;
double totalStandardDeviation;
int main(int argc, const char * argv[])
{
cout << "Please enter a list of numbers. When done enter the number 0 \n";
cin >> userInput;
while (userInput != 0) // As long as the user does not enter 0, program accepts more data
{
counter++;
x = userInput;
returnStandardDeviation( x, counter); // send perameters to function
cout << "Please enter next number \n";
cin >> userInput;
}
cout << "The standard deviation of your "
<< counter
<< " numbers is : "
<< returnStandardDeviation(x, counter);
return 0;
}
double returnStandardDeviation(double x, int counter)
{
x1 += pow(x,2);
x2 += x;
totalStandardDeviation = 0;
totalStandardDeviation += (sqrt(counter * x1 - pow(x2,2))) / (counter * (counter - 1));
return totalStandardDeviation;
}
NaN stands for "Not a number".
NaN can e.g. be the result of:
- Dividing by zero
- Taking the square root of a negative number
In your function, both of these could happen. Division by zero e.g. when counter is <= 1; and x1 and x2 are uninitialized (+= adds the value on the right to their current value - which was never set, and is therefore random gibberish), which can easily lead to your function trying to take the square root of some value < 0.
This expression
counter * x1 - pow(x2,2)
can very easily yield a negative number. You then proceed to take its square root. This would result in a nan.
Next, this one
counter * (counter - 1)
yields 0 when counter is 1. Dividing by zero gives nan.
Your formula is wrong. You are either dividing by zero or taking the square root of a negative number.
Check your formula!
Additional info:
NaN is "Not a number". It is an IEEE floating point value that signals an invalid results, like log(-1), or sqrt(-4).
Additionally, know that Positive Infinity and Negative Infinity are also floating point values.
I'm going through an O'reilly programming book, and one of the questions is to "write a program to average n elements".
This is the code that I have:
#include <iostream>
int n; //number of numbers
int number; //the numbers to be averaged
float avg; //the average of the elements
int counter; //iterator
int main()
{
std::cout << "Please enter the number of elements you want averaged: ";
std::cin >> n;
avg = 0;
counter = 0;
while (counter < n)
{
std::cout << "enter number: ";
std:: cin >> number;
number += number;
++counter;
}
avg = number/n;
std::cout << "Average of your " << n << " elements is: " << avg;
return 0;
}
For some reason, when I try to use 3 values of 3, i get a average of 2. I'm certain there's a problem with my declaration of "number" because it doesn't take the value of each number I enter and add it with each other. Could someone help me fix my mistake. I want my code to work for the general case; not just 3 elements. Thanks.
Two problems.
1)
std:: cin >> number;
number += number;
I assume that number is meant to be the sum of all numbers, but here you are also using it to store a single number, and when you assign a value to a variable it overrides what was already there. You must use two different variable names, such as
std:: cin >> number;
sum += number;
2)
number/n; is integer division since number is integer and n is integer. Integer division rounds down. Having the result of the expression assigned to a float is not enough - it is too late, the expression was already computed as integer division.
You want float division, so do sum/(double)n for example.
You read the number 3. The you say number += number, which makes it 6, and increment counter to 1. Then you read number again, it becomes 3, add it again, again 6, increment, counter. The third time, the same happens.
So you get 6/2 which is 3.
You read the input into number, but you aren't actually keeping a total of all the numbers entered which is what you really need for this problem.
#include <iostream>
#include <iomanip>
using namespace std;
int a[8], e[8];
void term (int n)
{
a[0]=1;
for (int i=0; i<8; i++)
{
if (i<7)
{
a[i+1]+=(a[i]%n)*100000;
}
/* else
{
a[i+1]+=((a[i]/640)%(n/640))*100000;
}
*/
a[i]=a[i]/(n);
}
}
void sum ()
{
}
int factorial(int x, int result = 1)
{
if (x == 1)
return result;
else return factorial(x - 1, x * result);
}
int main()
{
int n=1;
for (int i=1; i<=30; i++)
{
term(n);
cout << a[0] << " "<< a[1] << " " << a[2] << " "
<< a[3] << " " << a[4] << " " << a[5]<< " "
<< " " << a[6] << " " << a[7] << endl;
n++;
for (int j=1; j<8; j++)
a[j]=0;
}
return 0;
}
That what I have above is the code that I have thus far.
the Sum and the rest are left purposely uncompleted because that is still in the building phase.
Now, I need to make an expansion of euler' number,
This is supposed to make you use series like x[n] in order to divide a result into multiple parts and use functions to calculate the results and such.
According to it,
I need to find the specific part of the Maclaurin's Expansion and calculate it.
So the X in e=1+x+(1/2!)*x and so on is always 1
Giving us e=1+1+1/2!+1/3!+1/n! to calculate
The program should calculate it in order of the N
so If N is 1 it will calculate only the corresponding factorial division part;
meaning that one part of the variable will hold the result of the calculation which will be x=1.00000000~ and the other will hold the actual sum up until now which is e=2.000000~
For N=2
x=1/2!, e=previous e+x
for N=3
x=1/3!, e=previous e+x
The maximum number of N is 29
each time the result is calculated, it needs to hold all the numbers after the dot into separate variables like x[1] x[2] x[3] until all the 30~35 digits of precision are filled with them.
so when printing out, in the case of N=2
x[0].x[1]x[2]x[3]~
should come out as
0.50000000000000000000
where x[0] should hold the value above the dot and x[1~3] would be holding the rest in 5 digits each.
Well yeah Sorry if my explanation sucks but This is what its asking.
All the arrays must be in Int and I cannot use others
And I cant use bigint as it defeats the purpose
The other problem I have is, while doing the operations, it goes well till the 7th.
Starting from the 8th and so on It wont continue without giving me negative numbers.
for N=8
It should be 00002480158730158730158730.
Instead I get 00002 48015 -19220 -41904 30331 53015 -19220
That is obviously due to int's limit and since at that part it does
1936000000%40320
in order to get a[3]'s value which then is 35200 which is then multiplied by 100000
giving us a 3520000000/40320, though the value of a[3] exceeds the limit of integer, any way to fix this?
I cannot use doubles or Bigints for this so if anyone has a workaround for this, it would be appreciated.
You cannot use floating point or bigint, but what about other compiler intrinsic integral types like long long, unsigned long long, etc.? To make it explicit you could use <stdint.h>'s int64_t and uint64_t (or <cstdint>'s std::int64_t and std::uint64_t, though this header is not officially standard yet but is supported on many compilers).
I don't know if this is of any use, but you can find the code I wrote to calculate Euler's number here: http://41j.com/blog/2011/10/program-for-calculating-e/
32bit int limits fact to 11!
so you have to store all the above facts divided by some number
12!/10000
13!/10000
when it does not fit anymore use 10000^2 and so on
when using the division result is just shifted to next four decimals ... (as i assumed was firstly intended)
of course you do not divide 1/n!
on integers that will be zero instead divide 10000
but that limits the n! to only 9999 so if you want more add zeroes everywhere and the result are decimals
also i think there can be some overflow so you should also carry on to upper digits