0

Hi, everyone. You may have probably heard this a hundred times, but I am new to programming and I am taking an intro to C++ class. I have a program that I have written, but I can't understand why it will not exit gracefully.
This is what I have written, but if I type in "E" to exit, it loops to enter in a number again and doesn't exit.
printf("\nEnter one positive or negative number (1, 2, 3. . . or E to exit): ");

/*multiple lines comment - Program to display square and square root for a given number*/
#include <math.h>/*for sqrt( ) function*/
#include <stdio.h>
#include <stdlib.h>   
int main(void)
{
 /*variable and data type*/
 float x;
 
 /*standard output*/
 printf("Shannon says programming is hard!\n"); 
 printf("\nEnter one positive or negative number (1, 2, 3. . . or E to exit): ");
 /* Prompt for input again */ printf(">>  ");
 /*standard input*/
 scanf("%f", &x);
 printf("\nx = %f ", x);
 printf("\nSquare for x is = %f", x * x);
 //sqrt() is the predefined function, defined in math.h
 printf("\nSquare root for x is = %f\n", sqrt(x));//print results;
 return 0;//finished
}

Any help would be greatly appreciated!


<< moderator edit: added [code][/code] tags >>

2
Contributors
2
Replies
3
Views
11 Years
Discussion Span
Last Post by Starz20
0

This is what I have written, but if I type in "E" to exit, it loops to enter in a number again and doesn't exit.

I don't see the loop, but "E" is not a valid float number. If you want the possibility of the user input to be either text or a number, read the input as a string. Then, if the string is not "E", (attempt to) convert the input string into a float.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.