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
Related
Below is my code that should calculate the ISBN number of a book:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int isbn[] = 0;
printf("Please enter ISBN number: \n");
scanf("%d", &isbn);
int num = 0;
int times_by = 1;
long long sum;
long long sum1;
long long result = 0;
for (num = 0; num <= 9; num++){
sum = isbn[num] * times_by;
sum1 = sum + sum;
times_by++;
}
result = sum / 11;
if (result == 0){
printf("Yes\n");
}
else {
printf("No\n");
}
}
It is telling me that there is a problem with the initiator of isbn. I tried to create an array, which the inputted ISBN number would be saved to after, though Im not sure if this is possible..
The problem starts with int isbn[]=0; This declares an arry of no size, which can't be.
Then you read isbn as a single int and then you seem to want to calculate using each digit of the ISBN.
To do that, I suggest to declare char isbn[14]={0}; (ISBN can be 13 characters, see isbn).
Then read it as scanf("%13s", isbn);
and process it like:
sum = (isbn[num]-'0') * times_by; // convert digit to number
Note: sum1 = sum + sum; should be sum1 = sum1 + sum;
Note: result = sum / 11; should be result = sum1 / 11;
Note: you must initialize sum1: long long sum1=0;
Note: result = sum1 / 11; won't give you the remainder. Use result = sum1 % 11;
The line int isbn[] = 0; is your problem you are pointing the array's address to 0x0 which is not a valid address space for your application.
You should initialize your isbn array in another way. For example int isbn[20]. You should give a length which is sufficient for ISBN numbers. I just used 20 as an example.
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.
#include <math.h>
#include <stdio.h>
int main()
{
int n;
float per1, per2, per3;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for (int i = 0; i <= n - 1; i++)
{
if (arr[i] < 0)
{
int sum1 = sum1 + 1;
}
if (arr[i] > 0)
{
sum2 = sum2 + 1;
}
else
{
sum3 = sum3 + 1;
}
}
per1 = sum1 / n;
per2 = sum2 / n;
per3 = sum3 / n;
printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);
return 0;
}
output
3
1
-2
0
0.000000
0.000000
0.000000
the last three numbers should be .3,.3,.3 but it is giving zeros.
I think this code is a little bit better. I've used the function malloc() instead of the "scattered" declaration int arr[n] (in this case I prefer the old C style).
People already said you the problem relevant to the variable types and some ways to solve the problem. Here there's another way similar to the others you just saw between the answers.
#include <math.h>
#include <stdio.h>
#include <malloc.h>
#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"
int main()
{
int n, *arr=NULL;
float per1,per2,per3;
int sum1=0;
int sum2=0;
int sum3=0;
printf("How many number you have to insert? ");
scanf("%d",&n);
if (n<=0)
return 1;
arr=malloc(n*sizeof(*arr));
if (arr==NULL)
return 2;
printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
for(int i = 0; i < n; i++){
printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
scanf("%d",&arr[i]);
}
for(int i=0;i<=n-1;i++)
{
if(arr[i]<0){
sum1=sum1+1;
} else if(arr[i]>0){
sum2=sum2+1;
} else {
sum3=sum3+1;
}
}
per1=sum1; per1/=n; per1*=100.0;
per2=sum2; per2/=n; per2*=100.0;
per3=sum3; per3/=n; per3*=100.0;
printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);
if (arr!=NULL)
free(arr);
return 0;
}
Do floating point arithmetic like this
per1=sum1/(1.0*n);
per2=sum2/(1.0*n);
per3=sum3/(1.0*n);
How do you calculate percentage of some value? Your answers shouldn't be 1,1,1 but 33%, 33%, 33% for input you have. So your code should instead of this
per1=sum1/n;
be like this
per1=sum1*100.0/n;
And you have also got wrong your if conditions. The else part is tied only to second if. So every number less or equal to 0 is counted into sum3 which is not what you probably meant. So your
if (arr[i] > 0)
should have been
else if (arr[i] > 0)
And one last thing. On this line you are creating completely new variable sum1 that will live only to the end of the if statement and thus will not appear in the final calculation. I will leave it to you how to fix it.
int sum1 = sum1 + 1;
I don't know what environment you are using for development, but you should learn how to use debugger from the beginning. You can then peek into flow of your code to see what is going on and when it went wrong. With simple programs like this it is really easy. If you are on Visual Studio, they have really nice debugger integrated. Just set breakpoint and run Debug. If you are on Linux, there is gdb which might come pretty rough for beginners, but there are also graphical tools like ddd.
Since both sum1 and n are integers, the result of sum1/n is also an integer. This means that if sum1 is less than n, then the result of sum1 / n is 0.
To get a floating point result, at least one of the operands has be be float or double. I suggest you declare your sum variables to be double instead of int.
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.
First of all, I searched and all questions I found are similar but not exactly this one.
This is my first post here, I'm a beginner in programming and currently learning to code in C.
Been struggling with this code for about 5 hours now.
The question is create a program in C, using only loops (and not using pow(), using stdio.h library only).
The question is to get the user to give you two numbers - X and N
the program will print The result of the following equation:
1+2x+3x^2+4x^3+....+nx^(n-1)
For example for the input of - X=2 N=3
1*2^0 + 2*2^1 + 3*2^2
What the program will print is "17"
This is my attempt so far, I got to the Power function but I cant find a way to incorporate into the programm itself.
#include <stdio.h>
int main(void)
{
int i, j=0, b = 0;
float x, n;
double sum = 0, sumt=0;
do{
printf("Please enter two numbers \n");
flushall;
scanf("%f %f", &n, &x);
} while (x <= 0);
for (i = 1; i <= n; i++){
sum = x*x;
}
sumt += sum;
printf("%f", sum);
}
Instead of trying to create an implementation of pow, you will need to take advantage of the relationship between the terms of the expression.
The n-th term is nx^(n-1). The n-1-the term is (n-1)x^(n-2).
If we denote the n-th term as T(n) and denote the n-1-th term as T(n-1),
T(n) = T(n-1)*x*n/(n-1)
Given the starting value of the first term,
T(1) = 1
you can compute the subsequent terms using the above formula.
The following code should work.
// Initialize the values for N=1
term = 1;
sum = 1;
// Iterate starting from 2
for (i = 2; i <= n; i++){
term *= x*i/(i-1);
sum += term;
}
The working Program based on the tips given by the almighty #R_Sahu (And others ;D)
**
#include <stdio.h>
int main(void)
{
int i, j = 0, c = 0;
float x, n, b = 0;
double term, sum;
do {
printf("Enter Two Numbers\n");
flushall;
scanf("%f%f", &n, &x);
} while (x < 0);
for (i = 2; i < n + 2; i++)
{
term = 1;
sum = 1;
for (i = 2; i <= n; i++){
term *= x*i / (i - 1);
sum += term;
}
}
printf("The answer is %.lf ", sum);
}
I will not give you the code, but the reasoning you should follow
First you have to somehow get the data from the user (as a parameter, from stdio... whatever)
x = getFromUser
n = getFromUser
You will then need to init a temporary result
result = 0
How many times do you have to add? -> Exactly n times
for(ii=0;ii<n;ii++) {
result = result + pow((ii*x),(ii-1)) //There is something missing here, I'll let you guess what
}
But wait; you cannot use pow. So you have to program it by yourself (I guess that's the idea of the exercise)
then you need a function, and it has to return an int (actually, it may return even irrational numbers, but I don't think they will require you to do that)
int customPow(int base, int exponent) {
//Put your for in here, and may the pow be with you
}
You need to figure out the code yourself, but the general idea is as follows:
Create your own pow function which returns x*n.
int pow(int x, int n){
//use a for or while loop to calculate x (*x)n times.
//pay attention to the base cases (i.e., when n = 0, or 1 etc)
}
ans = 0;
for(i = 0 to N-1){
ans = ans + pow(x,i-1)*i;
}
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);