Hi I keep trying to figuure this out but my input keeps getting ignored, thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main(){
float a, b, a0, b0,i;
char ans;
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i ) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf(" %c", &ans);
while(ans == 'max'){
printf("maximum selected");
}
printf("minimum selected");
return 0;
}
CodePudding user response:
First of all, you're comparing a single char
to a whole string
, so you need to modify your ans
variable declaration to make it a string, like:
char ans[4]
Keep in mind, this will have a maximum size of 3
. If you need to store a bigger string
, you'll need to modify this.
Then, after doing this, using a while
to do that comparison isn't correct. It's better to implement an if-else
. And, inside that, the comparison you're doing is wrong. You need to compare strings
, not chars
, so you need to use strcmp()
function, like:
strcmp(ans,"max") == 0
If this function returns a 0
, it means both strings are equal.
Another thing to comment is that you will need to modify your scanf
to scan a string
, not a char
, the new one will be scanf("%3s", &ans);
.
And let me tell you one more thing. The for
you're using has no sense. You're using a for
with parameters i = 1; i <= 1; i
. That means i
will start the buckle fulfilling the conditions to break it, so it will only be executed once. In other words, the code inside that for
will be executed just once, no matter if it's inside or outside the for
.
Anyway, and to sum up, here's your new code:
int main(){
float a, b, a0, b0,i;
char ans[4];
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i ) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf("%3s", &ans);
if(strcmp(ans,"max") == 0)
printf("maximum selected");
else
printf("minimum selected");
return 0;
}