I've created a simple guessing game. Pick a number between 0 and 100, depending on the number you enter the program will output hot, Warm, Cold or correct!. The number I've chosen to be the correct answer is 51. My program compiles and runs but always outputs correct! for every value I enter. Thanks for helping if you decide to.
int main(void)
{
int number, answer;
answer = 51;
printf("Enter a number between 0 and 100:\n");
scanf("%d", &number);
if ((number > 51) && (number <= 56) || (number < 51) && (number >= 46))
{
printf("Hot\n");
}
else if ((number > 56) && (number <= 66) || (number < 46) && (number >= 36))
{
printf("Warm\n");
}
else if ((number > 66) && (number <= 100) || (number <36) && (number >= 0))
{
printf("Cold\n");
}
else if ((number > 100) || (number < 0))
{
printf("Error number has to be between 0 and 100 - re run\n");
}
else (number = 51);
{
printf("Correct!\n");
}
system ("pause");
return 0;
}
This little snippet:
else (number = 51);
{
printf("Correct!\n");
}
is actually equivalent to:
else
(number = 51);
//=======================
{
printf("Correct!\n");
}
The first part of that is the else clause which, if activated, will set number to 51.
The second part is totally disconnected from the if statement section and is a standalone block that will execute no matter what.
If you must put the condition there for readability (and it would be == rather than =), you could do:
else // (number == 51)
{
printf("Correct!\n");
}
As an aside, you could make your code shorter and more readable by starting at the specific and moving to the general, something like (just replacing the if statement):
if (number == 51)
printf ("Correct!\n");
else if ((number >= 46) && (number <= 56))
printf ("Hot\n");
else if ((number >= 36) && (number <= 66))
printf ("Warm\n");
else if ((number >= 0) && (number <= 100))
printf ("Cold\n");
else
printf ("Error, number has to be between 0 and 100 - re run\n");
}
You don't need to ever check the two ranges (above and below) for "temperature" since the inner ranges have already been checked.
else (number = 51);
{
printf("Correct!\n");
}
can be re-written as
else
{
number = 51;
}
{
printf("Correct!\n");
}
So irrespective of what your number is the printf("Correct!\n"); gets executed.
It can be fixed like
else
{
printf("Correct!\n");
}
remove the condition from the else statement.
int main(void)
{
int number, answer;
answer = 51;
printf("Enter a number between 0 and 100:\n");
scanf("%d", &number);
if ((number > 51) && (number <= 56) || (number < 51) && (number >= 46))
{
printf("Hot\n");
}
else if ((number > 56) && (number <= 66) || (number < 46) && (number >= 36))
{
printf("Warm\n");
}
else if ((number > 66) && (number <= 100) || (number <36) && (number >= 0))
{
printf("Cold\n");
}
else if ((number > 100) || (number < 0))
{
printf("Error number has to be between 0 and 100 - re run\n");
}
else
{
printf("Correct!\n");
}
return 0;
}
your code says: if none of the if statements is satisfied, assign 51 to number. and then always print "Correct!\n".
In the last else statement, you should either use
else if (number == 51)
{
...
}
or
else
{
...
}
Related
I am trying to make this short program work, but it gives a message of "expect expression" in the following part:
else
{
printf("program error!");
}
It looks like I am not using the if-elseif-else correctly. I've searched the web and found that the format is how I have it. Please help.
#include <stdio.h>
int main( )
{
double height, weight, bmi;
int bmievalcode;
while( 1 )
{
/* --> add code to input weight and height between here */
printf("Please enter weight in pounds and height in inches\n");
scanf("%lf %lf", &weight, &height);
bmi = (weight * 703.0)/(height * height);
bmievalcode = -1;
if (bmi < 18.5)
{
bmievalcode = 1;
}
else if (bmi >= 18.5 && bmi <25.0)
{
bmievalcode = 2;
}
else if (bmi >=25.0 && bmi < 30.0)
{
bmievalcode = 3;
}
else if (bmi >=30.0)
{
bmievalcode = 4;
}
/* bmievalcode:
* 1 = underweight
* 2 = normal
* 3 = overweight
* 4 = obese
*/
if (bmievalcode == 1 || bmievalcode == 2 || bmievalcode == 3 || bmievalcode == 4)
printf("bmi = %6.1lf, evaluation is ",bmi);
{
if (bmievalcode == 1)
printf("underweight");
else if (bmievalcode == 2)
printf("normal");
else if (bmievalcode == 3)
printf("overweight");
else if (bmievalcode == 4)
printf("obese");
printf(".\n");
}
else
{
printf("program error!");
}
}
return 0;
}
Your code is wrong here:
if (bmievalcode == 1 || bmievalcode == 2 || bmievalcode == 3 || bmievalcode == 4)
printf("bmi = %6.1lf, evaluation is ",bmi);
{
if (bmievalcode == 1)
printf("underweight");
else if (bmievalcode == 2)
printf("normal");
else if (bmievalcode == 3)
printf("overweight");
else if (bmievalcode == 4)
printf("obese");
printf(".\n");
}
else
{
printf("program error!");
}
The {} block isn't part of the if, it's separate. Then you have an else, but it's not directly after an if statement, which causes the error you see.
Move the line printf("bmi = %6.1lf, evaluation is ",bmi); to be after the opening {.
The statement directly after the if is what is affected by the condition. If this could compile, only that first printf would be conditionally executed. The curly-brace block would always run.
In this case, GCC is a little more helpful than Clang, telling you error: 'else' without a previous 'if'
I just started the CS50 course given by Harvard. I am currently working on the problem set 1 which is to validate a credit card number. How come my condition loop does not act like expected? For example, when I enter a credit card number of len 16 and that does not fit the conditions given (ex: 59e14), it will still print out "MASTERCARD"?
# include <stdio.h>
# include <cs50.h>
# include <math.h>
// Declaration of the functions
long get_number(void);
//const char * check_len(long cc);
void check_len(long cc);
// Main program
int main(void)
{
int i;
long credit_number = get_number();
printf("Validation for %ld\n", credit_number);
check_len(credit_number);
}
// Function that prompt the user for a credit card number
long get_number(void)
{
// Declaration of the credit card variable
long number;
// Ask the user for a credit card number. If it's not none-negative, keep asking
do
{
number = get_long("Enter credit card number: ");
}
while (number <=0);
return number;
}
// Function to check the type of credit card
void check_len(long cc)
{
// Declaration of variables
int i;
long number = cc;
// Count the len of the provided credit card number
for (i = 0; cc != 0; i++)
{
cc = cc/10;
}
printf("%i\n", i);
// Validate the type of card
if (i == 15)
{
if ( (number >= 34e13 && number < 35e13) || (number >= 37e13 && number < 38e13) )
printf("AMEX\n");
else
{
printf("INVALID\n");
}
}
else if (i == 13 || i == 16)
{
if ( (number >= 51e14 || number < 56e14) )
{
printf("MASTERCARD\n");
}
else if ( (number >= 4e12 || number < 5e12) || (number >= 4e15 || number <= 5e15))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
}
Given
if ( (number >= 51e14 || number < 56e14) )
...
51e14 is less than 56e14, so EVERY real number is either greater than 51e14 or less than 56e14.
If you want only numbers within that range, you need to use && so it satisfies both conditions:
if ( ( number >= 51e14 ) && ( number < 56e14 ) )
...
Your other conditions look to have similar problems.
So it compiles ok, but the output it is not the expected. The issue I think is in the OR operator which does not work properly, or it conflicts with the && operator. But perhaps it's bad written or something. Please let me know. Thanks in advance.
Here's the code:
if((len == 16) && secDigit == (51 | 52 | 53 | 54 | 55)
{
printf("MASTERCARD\n");
exit(0);
}
else if((len == 15) && secDigit == (34 | 37))
{
printf("AMEX\n");
exit(0);
}
else if((len == (16 | 13)) && firstDigit == 4)
{
printf("VISA\n");
exit(0);
}
else
{
printf("INVALID\n");
exit(0);
}
| is the Binary OR operator while what you need is || ,the Logical OR operator.
Syntax:
a|b
(Boolean 1) || (Boolean 2)
Note: Conditional operators evaluate to boolean values
if((len == 16) && (secDigit >= 51 && secDigit<= 55))
{
printf("MASTERCARD\n");
exit(0);
}
else if((len == 15) && (secDigit == 34 || secDigit == 37))
{
printf("AMEX\n");
exit(0);
}
else if((len == 16 || len == 13)) && firstDigit == 4)
{
printf("VISA\n");
exit(0);
}
else
{
printf("INVALID\n");
exit(0);
}
Say I have a few conditions inside a if statement:
if(x < 0 || x > 10 || x == 5)
{
}
If either x is greater than 10 or less than 0 or equal to 5, I want the program to stop working.
if(x < 0 || x > 10 || x == 5)
{
stop(); // PSEUDO CODE
}
However, I want the program to say something depending on which condition was true. Something like this:
if(x < 0 || x > 10 || x == 5)
{
if(x < 0)
{
printf("your number was less than 0");
}
if(x > 10)
{
printf("your number was greater than 10");
}
if(x == 5)
{
printf("wow, your number is equal to 5!");
}
stop(); // PSEUDO CODE
}
That's a horrible way of doing it because it unnecessarily checks for the conditions twice; how can I do the same in a more efficient way?
Why make things complicated? Just remove the outer check, and put stop() inside both of the inner ones:
if(x < 0)
{
printf("your number was less than 0");
stop();
}
if(x > 10)
{
printf("your number was greater than 10");
stop();
}
You can even use an else if if you want.
Save the boolean result in a variable and reuse it inside. Redundancy is ok sometimes. Just check/count the number of executions if it's possible to be lessen down.
bool isXNegative = x < 0;
bool isXMoreThan = x > 10;
bool isXFive = (x == 5);
//for specific conditions
if(isXNegative)
{
printf("your number was less than 0");
}
if(isXMoreThan)
{
printf("your number was greater than 10");
}
if(isXFive)
{
printf("wow, your number is equal to 5!");
}
//for combination of the conditions.
if(isXNegative || isXMoreThan || isXFive)
{
//common code here for all the conditions.
stop(); // PSEUDO CODE
}
//else if(another condition combination here...){...}
//else {...}
You can set a flag in the failure cases, then check the flag afterward to do the cleanup.
int do_stop = 0;
if(x < 0)
{
printf("your number was less than 0");
do_stop = 1;
}
if(x > 10)
{
printf("your number was greater than 10");
do_stop = 1;
}
if(x == 5)
{
printf("wow, your number is equal to 5!");
do_stop = 1;
}
if (do_stop) {
stop();
}
Assuming you do want to be complicated, save some keystrokes and take advantage of short-circuiting, you can assign expression results to variables in the if condition like so:
int c1, c2, c3;
if ((c1 = x < 0) || (c2 = x > 10) || (c3 = x == 5)) {
if (c1) {
printf("your number was less than 0\n");
} else if (c2) {
printf("your number was greater than 10\n");
} else {
printf("wow, your number is equal to 5!\n");
}
}
Just be aware that if the condition short-circuits (say x < 0), then the value of c2 and c3 is not initialized.
I don't actually advocate writing your code this way, but this language feature can be useful and I didn't see it mentioned.
The values entered are not matching with the output grade as it is giving 10 grade even when the conditions for 10 are not met.
the issue is that on entering hardness 50 strength 5600 and carbon 0.7 its giving grade 10 while for grade 10 carbon should be less than 0.7?
#include
#include
#include
int main() {
// program grade the steel on quality basis
int hardness;
int strength;
float carbon;
printf("Enter the hardness of steel:"); // condition 1 hardness should be >= 50
scanf("%d", &hardness);
printf("Enter the tensile strength:"); // condition 2 strength should be >= 5600
scanf("%d", &strength);
printf("Enter carbon content:"); // condition 3 carbon less than 0.7
scanf("%.2f", &carbon);
if ((hardness >= 50) && (carbon < 0.7) && (strength >= 5600)) { // all true
printf("\ngrade = 10");
}
else if ((hardness >= 50) && (carbon < 0.7) && (strength <= 5600)) { // 1 and 2 true
printf("\ngrade = 9");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength >= 5600)) { // 2 and 3 true
printf("\ngrade = 8");
}
else if ((hardness >= 50) && (carbon > 0.7) && (strength >= 5600)) { // 1 and 3 true
printf("\ngrade = 7");
}
else if ((hardness >= 50) && (carbon > 0.7) && (strength <= 5600)) { // any one true
printf("\ngrade = 6");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength <= 5600)) { // any one true
printf("\ngrade = 6");
}
else if ((hardness <= 50) && (carbon < 0.7) && (strength >= 5600)) { // any one true
printf("\ngrade = 6");
}
else {
printf("\ngrade = 5"); // none true
}
_getch();
return 0;
}
Use of "%.2f" as format specifier is not correct in scanf. It is good for printf but not scanf.
It's a good idea to always check the return value of scanf to make sure that the function was able to read the expected data.
if ( scanf("%.2f", &carbon) != 1 )
{
// Deal with error.
}
Add similar checks to the other scanf calls.
I think changing the above format specifier to "%f" should fix your problem. Add the check still.
if ( scanf("%f", &carbon) != 1 )
{
// Deal with error.
}
The problem is with the format specifier(.2f) in scanf statement.
%.2f is generally used to print 2 digits after the point
In C,all float literals are stored as double precision values.So we need to specify that we are using float i.e single precision by appending the values by f.Check the change of code
if you want your carbon to be rounded of to 2 digit precision, you can use carbon = ceilf(carbon*100)/100.0;
When you post your question next time, post your input for which it fails, you will get quick reply
And you can write this with less number of comparisons- here is the working code
#include<stdio.h>
int main(void) {
int hardness;
int strength;
float carbon;
printf("Enter the hardness of steel:");
scanf("%d", &hardness);
printf("Enter the tensile strength:");
scanf("%d", &strength);
printf("Enter carbon content:");
scanf("%f", &carbon);
if ((hardness >= 50) && (carbon < 0.7f) && (strength >= 5600))
printf("\ngrade = 10");
else if ((hardness >= 50) && (carbon < 0.7f))
printf("\ngrade = 9");
else if ((carbon < 0.7f) && (strength >= 5600))
printf("\ngrade = 8");
else if ((hardness >= 50) && (strength >= 5600))
printf("\ngrade = 7");
else if ((hardness >= 50) || (carbon > 0.7f) || (strength <= 5600))
printf("\ngrade = 6");
else
printf("\ngrade = 5");
_getch();
return 0;
}