Reputation: 3
The following is a portion of code that I am writing for a homework assignment in my EEL4834 class. This is just for practice and not for a grade.
My problem is that the compiler is treating my if statement as false when it is true. I believe it to be true because I test the statement by printing the value of my variable in the else statement, and the value that is printed for my variable is the value that I am asking in the if statement.
The code...
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char a, b, c, d, box;
float box1;
printf("\nPlease enter the box type as a, b, c, or d: ");
scanf("\n%c", &box);
if (box == a){
box1 = .05;
printf("%f", box1);
}
else{
printf("\n%c\n", box);
}
system("pause");
return 0;
}
The output looks something like this...
Please enter a box type as a, b, c, or d: a
a
Press any key to continue . . .
The output is telling me that box is in fact a, but if box is a then why isn't the compiler treating the if statement as true? I omitted the if statements that include options for b, c, or d for simplicity.
I apologize if this is something stupid. I tried to use the search engine and anything relevant seemed much more complex that my issue. Thanks in advance for any help.
Upvotes: 0
Views: 140
Reputation: 881583
if (box == a){
compares the variable box
against the variable a
(which is undefined).
You should probably compare it against the character:
if (box == 'a') {
That also means you can get rid of the variables a
, b
, c
and d
, since they're not used for anything:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char box;
float box1;
printf("\nPlease enter the box type as a, b, c, or d: ");
scanf("\n%c", &box);
if (box == 'a') {
box1 = .05;
printf ("%f", box1);
} else {
printf("\n%c\n", box);
}
system("pause");
return 0;
}
Upvotes: 3
Reputation: 38118
You're comparing against the variable named a
, and not the literal character 'a'
.
To understand what I mean, see a tutorial like this one
Upvotes: 1