Summation in C using Function - c

I was assigned to solve this problem using a function in C. I think I am going along the right lines as with the way the equation is set up now I get each individual instance of the summation, but I am stumped as to how to get the function to add the function together in the main function. Don't mind the naming convention, it is what's required for the assignment.
#include <stdio.h>
#include <math.h>
double doublef(double x,int i) {
double equation;
equation = pow(-1, i + 1) * (pow(x, i) / i);
return equation;
}
int main() {
for (int i = 1;i < 20;i++) {
double number1=doublef(0.3, i);
printf("f(0.3)=%f", number1);
}
return 0;
}
[Equation][1]
[1]: https://i.stack.imgur.com/YW8DK.png

#include <stdio.h>
#include <math.h>
double doublef(double x,int i) {
double equation;
equation = pow(-1, i + 1) * (pow(x, i) / i);
return equation;
}
int main() {
double number1=0;
for (int i = 1;i < 20;i++) {
number1+=doublef(0.3, i);
}
printf("f(0.3)=%f", number1);
return 0;
}

Related

Why is my function returning 0.0? (C code)

I've got a function that calculates the magnitude of a vector with a user specified size (dimension)
float VectorMagnitude(int vectorA[], int sizeVector)
{
float total = 0;
for (int i = 0; i < sizeVector; i++) {
total = total + (vectorA[i] * vectorA[i]);
}
total = sqrt(total);
return total;
}
if I print the result
printf("Magnitude of vector = %.2f\n", VectorMagnitude(Vec, size));
If I run the debugger with vectorA = {7, 5, 7} (with size being 3 obviously), the value of total just before I return it is 11.09... (which is correct).
However, the printed value is 0.0.
What am I doing wrong? (Its for a uni project so the random values are just fillers, I dont need to use actual values yet)
FULL CODE
main.c
#include <stdio.h>
#include <stdlib.h>
#include "matrixOperations.h"
int main()
{
int size;
printf("Enter size of vector:\n");
scanf("%d",&size);
int Vec[size];
FillMatrix(Vec,1,size);
DisplayMatrix(Vec,1,size);
printf("Magnitude of vector = %.2f\n",VectorMagnitude(Vec,size));
return 0;
}
matrixOperations.c
#include "matrixOperations.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/////////////////////////////////
void DisplayMatrix(int matrix[], int sizeRow, int sizeCol)
{ printf("Print matrix:\n");
for (int i=0;i<sizeRow;i++)
{
for (int j=0;j<sizeCol;j++)
{
printf("%d ", matrix[i*sizeCol+j]);
}
printf("\n");
}
printf("\n");
}
////////////////////////////////////////////////
void FillMatrix(int matrix[], int sizeRow, int sizeCol)
{
srand(time(0));
for (int i=0;i<sizeRow;i++)
{
for (int j=0;j<sizeCol;j++)
{
matrix[i*sizeCol+j]=rand()%10;
}
}
}
/////////////////////////////////////////////////////////////
float VectorMagnitude(int vectorA[], int sizeVector)
{
float total=0;
for (int i=0;i<sizeVector;i++)
{
total=total+ (vectorA[i]*vectorA[i]);
}
total = sqrt(total);
return total;
}
/////////////////////////////////////////////////////////////
matrixOperations.h
#ifndef MATRIXOPERATIONS_H_INCLUDED
#define MATRIXOPERATIONS_H_INCLUDED
#endif // MATRIXOPERATIONS_H_INCLUDED
You're missing #include "matrixOperations.h" in main.c ... err ... I mean: you're missing having a valid prototype in scope for the function (in the absence of a prototype C assumes the function accepts int arguments and returns int values)

How do I do a summation in C without math.c?

Hello I need to create this summation and if you put the number 30000 the response should the number of pi, however it's not working here's the summation and here's the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <ctype.h>
#include <stdbool.h>
int main( void ){
int num, k;
double pi= 0;
printf("Digite o total de termos >=30000: ");
scanf("%d", &num);
if (num < 30000){
printf("Erro.");
}else {
for (k = 1; k<= num; k++){
if (k % 2 == 0){
pi = (double)(-1)/ (2*k -1);
}else{
pi = (double)(1)/ (2*k -1);
}
pi = pi * 4;
}
printf("O valor de pi e %f", pi);
}
return 0; }
Here is a general way to sum things up:
double sum(int from, int to, double (*f)(int)) {
double ret = 0.0;
for(int i=from; i<to; i++)
ret+=f(i);
return ret;
}
And then you can write this function:
double fun(int current) {
double sign = current %2 == 0 ? -1.0 : 1.0;
return sign / (2*current - 1)
}
Finally, call it like this:
double pi = sum(1, num, fun);
Do note that this is probably not a good way to go if you're a beginner student that is looking for a solution to some homework.
#include <stdio.h>
int main(void) {
double pi=0;
for(int k=1; k<=3000; ++k)
{
pi += (2.*(k%2)-1) / (2*k-1); // This line does a summation, and uses floating point math (Not Integer Math)
}
printf("Pi : %f\n", 4*pi);
return 0;
}

Calculating a Serie in C

This image is the task I should do:
Whatever I enter between -1 and 1, the outputs are always 1.0000 or 2.0000. How can I do solve this problem? Below I attached my code.
#include <stdio.h>
#include <math.h>
int main() {
int i;
float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
if ((x>-1)&&(x<1))
{
for (i=0;i<101;i++)
sum= sum + (pow(x,i));
}
printf ("result=%f",sum);
return 0;
}
if ((x>-1)&&(x<1))
With this case your code will work only if x is zero so try removing if statement and do mention what output you expect for given particular input, it will be bit more helpful to answer it.
Try this code:
#include <stdio.h>
#include <math.h>
int main() {
int i; float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
for (i=0 ;i<101; i++)
sum+= (pow(x,i));
printf ("result=%f",sum);
return 0;
}
Even upon using a type like double you haven't got enough numerical precision to sum all the powers up to 100.
Executing the following snippet, you'll notice that, while the correct (numerically speaking) result is evaluated, the loop stops way before the 100th iteration, typically at 16:
#include <stdio.h>
#include <math.h>
#include <float.h>
// Analytically calculates the limit for n -> inf of the series of powers
double sum_of_powers_limit(double x)
{
return 1.0 / (1.0 - x);
}
int main(void)
{
double x = 0.1;
const int N = 100;
double sum = 1.0;
for (int i = 1; i <= N; ++i)
{
double old_sum = sum;
sum = sum + pow(x,i);
if (old_sum == sum)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
printf(" result = %.*e\n", DBL_DECIMAL_DIG, sum);
printf("expected = %.*e\n", DBL_DECIMAL_DIG, sum_of_powers_limit(x));
return 0;
}
Also note that a more efficient way to evaluate this kind of polynomials is the Horner's method:
// Evaluates the sum s(x) = 1 + x + x^2 + ... + x^n using Horner's method
// It stops when it cannot update the value anymore
double sum_of_powers(double x, int n)
{
double result = 1.0;
for (int i = 0; i < n; ++i)
{
double old_result = result;
result = 1.0 + x * result;
if (old_result == result)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
return result;
}

Functions different datatypes calculate rent

trying to make a function which calculate the total sum with rent of a starting amount.
My printf("%.1f", calcFutureValue[i]); don't want to work for some reason, i did a lookup if it had to do with the different datatypes, since numberOfYears is an int but not sure.
What i'am missing?
#include <stdio.h>
#include <math.h>
double calcFutureValue(double startingAmount, double interest, int numberOfYears);
int main()
{
double startingAmount = 10000;
double interest = 1.045;
int numberOfYears = 3;
calcFutureValue(startingAmount, interest, 3);
for (int i = 0; i < numberOfYears; i++)
{
printf("%.1f", calcFutureValue[i]);
}
getchar();
return 0;
}
double calcFutureValue(double startingAmount, double interest, int numberOfYears)
{
for (int i = 0; i < numberOfYears; i++)
{
startingAmount * interest * pow(numberOfYears, 2);
}
getchar();
}
Try this code:
#include <stdio.h>
#include <math.h>
double calcFutureValue( int numberOfYears);
const double startingAmount = 10000;
const double interest = 1.045;
int main()
{
int numberOfYears = 3;
int i;
for (i = 0; i < numberOfYears; i++)
{
printf("%.2f\n", calcFutureValue(i));
}
return 0;
}
double calcFutureValue(int numberOfYears)
{
return startingAmount * pow(interest, numberOfYears);
}
Explanation:
There was a mistake with the compound interest formula.
Since this is dealing with currency, the decimal width of 2 is appropriate.
Since startingAmount and interest are constants, they can be constant global variables.

Segmentation fault when using different functions

I'm trying to separate my code more neatly by using functions. An issue I've been having is passing variables through different functions. If I leave all my code in my working function it will run no problem. It's when I create another function and pass variables to that function, that's when I get the issues.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
workings();
output();
}
void workings()
{
int x;
int i;
double total = 0;
double squareRoot;
double overall;
scanf("%d", &x);
int* array = malloc(x * sizeof(int));
if (!array) {
printf("There isn't enough memory \n");
return;
}
int j = 0;
while (j < x) {
scanf("%d", &array[j]);
total += array[j] * array[j];
j++;
}
squareRoot = sqrt(total);
}
void output(int x, double overall, double squareRoot, int* array)
{
int k = 0;
while (k < x) {
overall = array[k] / squareRoot;
printf("%.3f ", overall);
k++;
}
}
You must pass arguments to functions which require them.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void workings(int *x_out, double *squareRoot_out, int** array_out);
void output(int x, double squareRoot, int* array);
int main(void)
{
int x;
double squareRoot;
int* array;
workings(&x, &squareRoot, &array);
output(x, squareRoot, array);
}
void workings(int *x_out, double *squareRoot_out, int** array_out)
{
int x;
double total = 0;
double squareRoot;
scanf("%d", &x);
int* array = malloc(x * sizeof(int));
if (!array) {
printf("There isn't enough memory \n");
return;
}
int j = 0;
while (j < x) {
scanf("%d", &array[j]);
total += array[j] * array[j];
j++;
}
squareRoot = sqrt(total);
/* pass data for later use to callee */
*x_out = x;
*squareRoot_out = squareRoot;
*array_out = array;
}
void output(int x, double squareRoot, int* array)
{
double overall;
int k = 0;
while (k < x) {
overall = array[k] / squareRoot;
printf("%.3f ", overall);
k++;
}
}
Changes I made are:
Add prorotype declaretions of functions to be used before main() (where the functions are used).
This is for safety: compilers cannot check arguments before knowing declaretions nor definitions of functions.
Add arguments to workings() in order to export data used in the function.
Use the arguments to export data.
Remove variables overall and i in workings() because they weren't used.
Remove overall parameter from output() function and declare it as local variable because the input is not used.
Modify main() function to allocate memory for passing data and pass data between functions.

Resources