Algorithm in C loop of for repeating response

Asked

Viewed 47 times

0

Guys I’m going to college and I got stuck in a list exercise, it’s a C algorithm, could help me

My problem is that I put a number to serve the variable x and it calculates about 4 times properly, the numbers come out different, then the result comes out all the same, until you give the loop 10 times, thanks for the help

#include <stdio.h>

int main() {
  float x, m, e, h, y, n, f, b, l, k, w;
  int s;
  printf(“Digite um valor para o angulo em radiano\ n”);
  scanf("%f", & x);
  w = 0;
  k = 0;
  y = 0;
  h = 1;
  f = 0;
  for (s = 1; s <= 8; s++) {

    b = s % 2;

    /*Colocar o valor positivo e negativo usando o if*/
    if (b == 0) {
      w = w + 2;
      y = pow(x, w);
      y = y * (-1);
    } else {
      w = w + 2;
      y = pow(x, w);
      y = y * 1;
    }

    /*Calculo do fatorial*/
    k = 1;
    f = f + 2;
    m = f;
    for (; m > 0; m = m - 1)
      k = m * k;

    /*resultado final*/
    h = y / k + h;
    printf("%f\n", h);
  }
  return 0;
}
  • 2

    hello, variables may have more significant names, for example "value", "calculation", "angle", etc.. float x, m, e, h, y, n, f, b, l, k, w; This here is very bizarre and bad to read :) looking at this bunch of variables I can’t understand their purpose, it’s even difficult to help. Ah, that line for (; m > 0; m = m - 1) would be better off like this for (m = f; m > 0; m--)

  • You did not present the values used in the tests but here h = y / k + h; depending on the value of k (that is f!) the result of the division may be zero and for significant purposes may not interfere with the value of h.

1 answer

0

Hello, I noticed that your code has some redundancies, for example equal commands within the if and in Else, unused variables and did not include the mathematical library to use the Pow function, I advise to fix this. I didn’t understand the purpose of your program, but I realized that the repetition of equal results is due to the lack of precision in the decimals, that is, the latest results differ in a quantity less than 10 -6 and so it is not possible to notice that they are different since the float shows up to 6 decimal places, if multiplying the result in Y is remarkable that

#include <stdio.h>
#include <math.h>
int main() {
  double x, m, h, y, f, b, k, w;
  int s;
  printf("Digite um valor para o angulo em radiano\n\t");
  scanf("%lf", &x);
  w = 0;
  k = 0;
  y = 0;
  h = 1;
  f = 0;
  for (s = 1; s <= 8; s++) {

b = s % 2;

/*Colocar o valor positivo e negativo usando o if*/

w = w + 2;
y = pow(x, w);

if (b == 0) {
  y = y * (-1);
}

/*Calculo do fatorial*/
k = 1;
f = f + 2;

for (m=f ; m > 0; m--){
    k = m * k;
}


/*resultado final*/
h = 1000000000*y / k + h;
printf("%lf\n", h);
}return 0;}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.