0
How do I find max y(x), cause now it's only showing x max
2 Réponses
+ 1
This code works:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <locale.h> // for setlocale function
//[a,b]=[-3, 4]
//h=1
int main( )
{ setlocale(0, "");
double a, b, c, x, y;
double max = -0x10000000;
// start with a very small number that will
// get replaced immediately.
printf (" [a,b]: ");
scanf ("%lf", &a);
scanf ("%lf", &b);
printf (" h: ");
scanf ("%lf", &c);
printf ("--------------------\n");
printf ("x\t|\tf(x)\n");
printf ("--------------------\n");
x = a;
do
{
y = pow(x, 3) - 2*pow(x,2) + x - 1;
printf ("%.2lf\t|\t%.2lf\n", x, y);
x = x + c;
if (y > max)
max = y;
}
while (x <= b);
printf("max = %.2f\n", max);
}
I made the following changes:
- changed max from int to double. Assigning y(a double) to max(an int) made no sense. It looked like you wanted max to be the maximum of all calculated y values. If the value had a decimal or fractional part to it, you should use a data type that can capture that.
- removed an if-statement that was erroneously assigning a value to a variable in its condition. I think you meant max == y instead of max = y but that also seemed odd and pointless. Removing the if-statement looked closer to what you'd want.
- Instead of assigning y to max after the do-while loop, I continually checked and updated max to maintain the current max. What you had assumed that the loop ended with y being the largest value it ever was. I didn't want to make that assumption.
- locale header was added to define setlocale function.
- A few unused variables like f were removed.
0
Josh Greig thank you so much)