Why won't my program work? It is supposed to add numbers from a formula 1-(1/2)+(1/3)...+(1/999)-(1/1000)=
#include <stdio.h>
#include <math.h>
int main () {
int i, j;
float suma;
suma = 0.f;
for (i=0; i<1000; i++) {
if (i%2==0) {
suma=suma - 1/i;
} else {
suma=suma + 1/i;
}
}
printf("%f", suma);
}
Divide by zero !!
int main () {
int i;
float suma;
suma = 0.0f;
for (i=1; i<1000; i++) { //fix loop, start from 1
if (i%2==0) {
suma=suma - 1.0f/i; // Use 1.0, (1/i will be evaluated as int)
} else {
suma=suma + 1.0f/i;
}
}
printf("%f", suma);
}
Try printing 1 / i with i being an int. This will always returns 0, except when i is 1. This happens because 1 / i is evaluated as an Euclidean division with the remainder being discarded.
The reason this is evaluated like this is because 1 and i are both integer.
You need to either the numerator or the denominator to be of floating point type.
One way is to cast i to a float, so your code would look like this: suma = suma - 1 / (float)i. The other way is to make 1 be of floating point type: suma = suma - 1.0 / i or suma = suma - (float)1 / i.
The for loop started from 0.
so the first iteration returns divide by zero error.
second iteration will return 1/1=1 and will work good, but from third iteration it will return 0, because you are using int. Try starting the for loop from 1 and typecast i to float.
You will get much higher accuracy if you apply some math first. Your series:
1 - 1/2 + 1/3 - 1/4 + ... + 1/999 - 1/1000
can be rewritten as:
(1 - 1/2) + (1/3 - 1/4) + ... + (1/999 - 1/1000)
or as:
1/(1*2) + 1/(3*4) + ... + 1/(999*1000)
Now, you can write a program to perform calculation. However, you should use double type to improve accuracy and cast integer to double to make sure that your series are added as double numbers:
#include <stdio.h>
#include <math.h>
int main() {
int i;
double sum = 0;
for (i=1; i<1000; i+=2) {
sum += 1/(i*(i+1.)); // 1. to force cast to double
}
printf("%g", sum);
}
herein a simple program
float j = 1.0f;
float suma = 0.0f;
int i = 1;
for (i=1; i <= 1000; i++) {
suma += j/i;
j = j * (-1);
}
Related
C program for first seven terms in natural logarithm. I am not getting the right answer, can anyone review the following code.
#include<stdio.h>
int main(){
float x,i,sum,result=0;
printf("Enter value of x:");
scanf("%f",&x);
for(i=2;i<=7;i++)
{
sum = (x - 1)/x;
result = (sum + (0.5 * pow(sum,i)));
}
printf("Sum of series of Natural Logarithm is: %0.2f",result);
return 0;
}
You haven't implemented the series correctly.
The iteration should begin at 1
The 0.5 is only correct for the second term
You overwrite result from each term instead of summing it.
Here is the corrected code. I also changed float to double, and i to int.
#include <stdio.h>
#include <math.h>
int main(void)
{
double x, sum, result = 0;
int i;
printf("Enter value of x: ");
int res = scanf("%lf", &x);
if(res != 1 || x <= 0.5) // validate
return 1;
for(i = 1; i <= 7; i++)
{
sum = (x - 1) / x;
result = result + pow(sum,i) / i;
}
printf("Sum of series of Natural Logarithm is: %f\n", result);
printf("The library function log() calculates: %f\n", log(x));
return 0;
}
Program session
Enter value of x: 0.75
Sum of series of Natural Logarithm is: -0.287697
The library function log() calculates: -0.287682
I'm facing problems in writing a program in C that calculates S, being S = {1/50 - 3/48 + 5/46...} with 9 elements. I don't know how to use the DIFFERENCE operator followed by a SUM operator, and I MUST use the for structure.
Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, d, S, i;
i = 0;
n = 1;
d = 50;
S = n / ((double)d);
for (i = 0; i < 4; i++) {
n += 2;
n -= 2;
S = S + (n / ((double)d));
S = S - (n / ((double)d));
}
printf("%d", S);
return 0;
}
I know that the variable declarations may be wrong and that's exactly where I get confused. I decalred S as an integer but put d (denominator) to double 'cause the result must be a decimal number, of course.
Can anybody help me??
The output I'm getting is: 0
Perhaps like this. The most important point, is to use the double type, because the int type can only hold whole numbers.
#include <stdio.h>
int main (void) {
int i;
double sign = 1.0; // sign
double num = 1.0; // numerator
double div = 50.0; // divisor
double sum = 0.0; // series sum
for (i = 0; i < 9; i++) {
sum += sign * num / div; // accumulate the term
num += 2.0; // numerator +2
div -= 2.0; // divisor -2
sign *= -1.0; // alternate the sign
printf("%f\n", sum); // show double result
}
return 0;
}
Program output:
0.020000
-0.042500
0.066196
-0.092895
0.121390
-0.153610
0.188496
-0.228171
0.271829
Different things to say about your code.
First you cannot use an integer for your sum since you want a floating point result.
Then as mentioned in comments you are using successive operations that result in not changing the variable
n+=2; n-=2;
You could simply do something like :
double S = 0.0; int N=9;
for(i=0; i < N; ++i) {
S += ( (i % 2 == 0)?(1.0):(-1.0) ) * (2.0*i+1)/(50-(2.0*i+1));
}
The instruction (i % 2 == 0)?(1.0):(-1.0) pick 1 if 'i' is even and -1 if 'i' is odd.
Finally if S is no longer an int you must change your printf with a floating point format like for example '%f'.
Check if what you're looking for is the following code:
#include <stdio.h>
#include <stdlib.h>
void main () {
int n = 1, d = 50, i = 0, signal = 1;
double S = n / (double) d;
for (i = 0; i < 8; i++) {
n += 2;
d -= 2;
signal = -signal;
S += signal * n/(double)d;
}
printf("%f", S);
}
I think you're missing S is a double number. int/double = double, but youre assign this math in a int variable.
I am trying to calculate an arithmetic, geometric, and harmonic mean as well as a standard deviation, after prompting a user to input 5 integers.
I have the arithmetic mean working well. Its the others after it that are troublesome.. I am almost positive it is because of my structuring, but I just am not sure what to change after researching online and in my textbook... and any help is appreciated with this!
Here is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
float a_mean;
float g_mean;
float h_mean;
float st_dev;
sum1 = 0; sum2 = 0; sum3 = 0;
float data[100];
n = 5;
int i;
int main()
{
printf("Please Enter Five Integers:\n"); /* Prompts user input */
for ( i = 0; i < n; ++i)
{
scanf("%f", &data[i]);
sum1 = sum1 + data[i];
}
a_mean = sum1 / n;
{
sum2 = sum2 * data[i];
}
g_mean = pow(sum2, 1 / n);
{
sum3 = sum3 + ( 1 / data[i] );
}
h_mean = n / sum3;
printf("Arithmetic mean: %0.2f\n", a_mean);
printf("Geometric mean: %0.2f\n", g_mean);
printf("Harmonic mean: %0.2f\n", h_mean);
return 0;
}
I know its probably something basic with my for-structuring, but I simply don't know a lot about this stuff yet, so thanks in advance
**Also, disregard the fact that I haven't attempted to form my calculation/output for the standard deviation yet. Thanks
Either do all of your summing inside the one for loop
or do three for loops.
Since you are beginning try both!
Here is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
float a_mean;
float g_mean;
float h_mean;
float st_dev;
sum1 = 0; sum2 = 0; sum3 = 0;
float data[100];
n = 5;
int i;
int main()
{
printf("Please Enter Five Integers:\n"); /* Prompts user input */
for ( i = 0; i < n; ++i)
{
scanf("%f", &data[i]);
sum1 = sum1 + data[i];
sum2 = sum2 * data[i];
sum3 = sum3 + ( 1 / data[i] );
}
a_mean = sum1 / n;
g_mean = pow(sum2, 1 / n);
h_mean = n / sum3;
printf("Arithmetic mean: %0.2f\n", a_mean);
printf("Geometric mean: %0.2f\n", g_mean);
printf("Harmonic mean: %0.2f\n", h_mean);
return 0;
}
Your problem is that the for loop will only run the scanf, and then change sum1. You need to move your sum2 = sum2 * data[i] and sum3 = sum3 + (1 / data[i]) into the body of the for loop (Inside the {}s right after the for loop).
First of all - your code doesn't compile, you're missing a bunch of types in the global variables. Second - you can't break up the loop and continue just by using curly brackets, the few sets you have after the first loop would just be executed once as normal code, so the other sums aren't collected properly.
As for style - try to use less globals, it's a bad habit
This is what I came up with:
#include <stdio.h>
int main (void)
{
int n, i, j;
float e = 1.0, nFact = 1.0;
printf ("please enter the number");
scanf ("%d", &n);
for (i = 1; i <= n ; i++)
{
for (j = 1; j <= i; j++)
{
nFact *= j;
}
e = e + (1.0 / nFact);
}
printf ("The value of 'e' is : %f", e);
return 0;
}
This is what I get from this code.
Input: 3
Output: 2.58333 (which is close to 2.6666...)
But for n=3, e should give 2.6666.. as a value.
Am I doing something wrong here? How can I get the proper output?
You are needlessly calculating the factorial in every iteration. Just replace the inner loop by nFact *= i;.
#include<stdio.h>
int main (void)
{
int n,i,j;
float e=1.0, nFact=1;
printf("please enter the number");
scanf("%d", &n);
for( i =1; i<= n ; i++)
{
nFact*=i;
e = e + (1.0/ nFact);
}
printf("The value of 'e' is : %f", e);
return 0;
}
Am i doing something wrong here?
You have forgotten to set the factorial variable to one. So, your variable is getting smaller quickly. This makes (1.0/nFact) even smaller and that is why you get smaller e.
nFact=1.0; //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1 ; j <= i; j++)
{
nFact *= j;
e = e + (1.0/ nFact);
}
//only single loop is more than enough
You are getting your factorial by O(n) complexity. Why not save the old value and use it in every iteration?(O(1)--->no need the factorial-loop. Just use old value since you are not resetting it. (Just multiply by i)
how can i get the proper output?
After the 11st or 12th iteration, your float would not give enough precision-resolution-minimum step. Double or BıgDecimal seems better if your going for science.
That loop is very inefficient: Note how your inner loop computes the same thing over and over!
Instead, you should keep a running term and update it:
double term = 1;
double result = term;
for (unsigned int i = 1; i != n; ++i)
{
term /= i;
result += term;
}
printf("With %u steps we compute %f.\n", n, result);
Can some one please help me on this issue as I have spent time going around it without making any headway.
I have data in an array of size say 3O.
I want to take the first five elements of the array, find their mean value. Store the value in another array
Then move to the second element of the array,from their find the mean value of the 5 succeeding elements.store the value in the array as above.
Then wove to the 3rd element,do the same thing above till the last element which is 30 in this case.
float tabdata[] = {1,2,3,4,...,30};
char *store;
float sum;
for(int j=0;j<tabdata[30-1];j++)
sum += tabdata[j];
if (j=5)
{
float mean= sum/5;
store[j]=mean;
sum=0;
for(i=j;i>tabdata[30-1];i++)
sum +=tabdata[i];
if (j=5)
---
----
....need help to complete this loop please.
Just add 1/5 of the next element and subtract 1/5 of the first element in the current window at every step. The only thing you need to worry about is floating point precision.
You can fix up the sum as you go:
#include <stdlib.h>
#include <stdio.h>
int main()
{
float tabdata[] = {1,1.5,1.8, 2, 3, 4, 5,6,7,8,9,10,11,12,13,14,15,161,7,18,19,20,21,30};
float* result;
float sum;
int count = sizeof(tabdata)/sizeof(tabdata[0]);
int i;
result = (float *)malloc((count - 4) * sizeof(float));
/* Initialise with the first five elements */
for (i=0;i<5;i++)
{
sum += tabdata[i];
}
result[0] = sum / 5.0;
for (i=5;i<count;i++)
{
sum -= tabdata[i-5];
sum += tabdata[i];
result[i-4] = sum / 5.0;
}
for (i=0;i<count-4;i++)
{
printf("%f\t%f\n",tabdata[i],result[i]);
}
for (;i<count;i++)
{
printf("%f\n",tabdata[i]);
}
free(result);
}
I think that what you might want to use is the modulus operator (%) which will give you the rest of the division. You will get something like this:
if ((j+1) % 5 == 0)
{
float mean= sum/5;
store[j/5]=mean;
sum=0;
}
This way, at every 5 iterations, the code will be executed.
Haven't tested this but should work:
float tabdata[] = {1, 2, 3, ..., 30};
float *result;
float sum;
int count = sizeof(tabdata)/sizeof(tabdata[0]);
result = (float *)malloc((count - 4) * sizeof(float));
for (int j = 0; j < count - 5; j++) {
sum = 0;
for (int k = j; k < j + 5; k++) {
sum += tabdata[k];
}
result[j] = sum / 5;
}
// ...
free(result);