C - Loop, <math.h>, and float - c

#include <stdio.h>
#include <math.h>
int main()
{
int i;
int result;
float f;
while((result = scanf("%d", &i)) != EOF)
{
scanf("%f", &f);
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");
return 0;
}
Hi,
I just began with C and I'm having a problem solving a question.
The problem is that with the user input, I need to get three sets of numbers that are floored, rounded, and ceiled. This process must be ongoing until the user stops by EOF command (Ctrl-D).
When I run my code above, input a value 3.1415, I get 0 0 1 as an output, which is wrong because it's supposed to be 3 3 4.
Any suggestions or help on how to fix the problem would be appreciated.

According to your code, you first need to input an integer value and then enter a float value.
OR, you can start accepting float value like this:
#include <stdio.h>
#include <math.h>
int main()
{
int result;
float f;
while((result = scanf("%f", &f)) != EOF)
{
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");
return 0;
}

According to your code you need to input integer first then float, But if you enter float value first, that value read by i first and return 0 that is !=EOF, so second scanf does not wait for input, because it is inside the while loop. So always you will get 0 0 1 for all inputs!
To scan a number inside while loop use-
if (scanf("%f", &f) == 0) {
printf("Err. . .\n");
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
Else scan float value first instead of int and float. Try this code-
while((result = scanf("%f", &f)) != EOF)
{
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");

Related

Isalpha is requiring an identifier

Here's my code:
#include <stdio.h>
#include <ctype.h>
main(){
float input;
printf("Input: ");
scanf("%f", &input);
if (isalpha(input) || (input) < 0)){
printf("Input is an alphabet or is lesser than 0");
} else {
printf("Input is correct. %f is a number larger than 0", input);
}
}
I want the code to detect if input is a number larger than 0, or is it an alphabet. However, I am getting this error:
8: error: identifier expected
What does it mean to my code's execution? How am I supposed to run the code successfully?
Correct parentheses in if:
if ( isalpha(input) || (input < 0) )
In addition, you need to check the return value of scanf() whether there was input or not. In the case of no input, the return value would be 0 or in case of multiple inputs how many succeeded. In your case, you can use the return value to determine whether a float was input or not.
The main() should return an int and always initialize your variables.
Example (live):
#include <stdio.h>
#include <ctype.h>
int main()
{
float input = 0.0f;
printf("Input: ");
int ret = scanf("%f", &input);
if ( ret == 0 )
{
printf("ERROR: Input is NOT a float!\n");
return -1;
}
if ( input < 0.0f )
{
printf("Input is less than 0");
}
else
{
printf("Input is correct. %f is a number larger than 0", input);
}
return 0;
}
Your parentheses aren't opened/closed properly.
Maybe your ide/compiler is taking care of it, but it should be int main()
isalpha() will behave unexpectedly with float values. Try avoiding that.
First of all you are missing int declaring main,
int main()
Also,you have excessive bracket in line
if (isalpha(input) || (input) < 0)){
Scanf uses %f to read floats. What your program will do is accept any ascii character and I suppose that wasn't your intention.
I am still not sure what you need, but you could try something like this as a starting point. It does not handle all possible inputs, and will erroneously classify an input such as #42 as alphabet or lesser than 0, which is questionable, but you can iterate on this and hopefully get to a more polished version.
#include <stdio.h>
#include <ctype.h>
int main(){
float input;
printf("Input: ");
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
} else {
printf("Input is an alphabet or is lesser than 0");
}
}
Explanation
We save the value in input, if compatible with the %f format:
float input;
Prompt for the user:
printf("Input: ");
This condition is made of two parts; the first part is the scanf, that will try to read input, and if successful will evaluate to 1, which is true, so the second part input >= 0 will be evaluated, and if input is indeed >= 0 we print the first message.
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
Else we print the second message.
} else {
printf("Input is an alphabet or is lesser than 0");
}

Reprompting user when negative float value input

so I'm a complete newb to C and I'm struggling with the language. I need to write a program that will re-prompt a user to input a number if they input a negative number untill they produce a positive one. I have the below so far, no error messages are showing but when I type in a negative float value it does not re-prompt me, it just displays the number. Any ideas?
#include <cs50.h>
#include <stdio.h>
#include <math.h>
float get_positive_float(string prompt);
int main(void)
{
float f = get_float("Cash: ");
printf("%f\n", f);
}
float get_positive_float(string prompt)
{
float n;
do {
n = get_float("%s", prompt);
} while (n < 0);
return n;
}
float get_positive_float(char const *prompt)
{
float result;
while (prompt && printf(prompt), scanf(" %f", &result) != 1 || result < 0.f) {
fputs("Please only enter positive values!\n\n", stderr);
for (int ch; (ch = getchar()) != '\n' && ch != EOF;); // clear the rest of the line
}
return result;
}
A version using the thingies from <cs50.h> might look like that:
float get_positive_float(string prompt)
{
float result;
while ((result = get_float(prompt)), result < 0.f) {
fputs("Please only enter positive values!\n\n", stderr);
}
return result;
}
The problem though is, that floating point numbers aren't suitable for amounts of money. Use an integer type and calculate in cents. For output divide by 100.

Is it possible to ignore certain characters in "scanf_s"?

So here is my code. Its a school assignment. I had to make a program to calculate the square root of a number using a method the Babylonians developed etc, that's not the important part. What I was wondering is if it's possible to ignore letters in my scanf so that when I input a letter it doesn't go berserk in my terminal. Any help is welcome and greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double root_Approach(double s); // defines the two functions
void ask_Number(void);
int main() {
ask_Number(); // calls function ask_Number
printf("\n\n");
system("pause");
return 0;
}
double root_Approach(double s) {
double approach;
approach = s;
printf("%.2lf\n", s); // prints initial value of the number
while (approach != sqrt(s)) { // keeps doing iteration of this algorithm until the root is deterimened
approach = (approach + (s / approach)) * 0.5;
printf("%lf\n", approach);
}
printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes
return approach;
}
void ask_Number(void) {
double number;
while (1) {
printf("Input a number greater than or equal to 0: "); // asks for a number
scanf_s("%lf", &number); // scans a number
if (number < 0) {
printf("That number was less than 0!!!!!!\n");
}
else {
break;
}
}
root_Approach(number);
}
Scanf reads whatever may be the input from the terminal (character or integer)
One way you can do is to check the return statement of scanf whether the read input is integer or not an integer.
Here is the sample code
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
`
this link may be helpful
Check if a value from scanf is a number?

How to limit user to input a float with one decimal point in C

Program to limit the user's input to one decimal point in C.
For example:
Enter grade: 5 //Acceptable
Enter grade: 8.5 //Acceptable
Enter grade: 6.467 //Not acceptable, Re-enter grade
#include <stdio.h>
#include <math.h>
main()
{
double grade[8];
int i;
for (i = 0; i < 8; i++) {
printf("Insert grade: ");
scanf("%f", &grade[i]);
}
}
You will have to input the data as string, then check it only has one decimal place.
It is not possible to input a floating-point value and then check for decimal places; since the floating point values are stored internally with binary places and hold an approximation of the value that was input, in most cases.
The input code could look like:
char temp[20];
if ( 1 != scanf("%19s", temp) )
return EXIT_FAILURE;
// code to check for decimal place goes here - I'm purposefully not
// showing it as this looks like homework!
// once we have checked that the input is correct, then convert to double
grade[i] = strtod(temp, NULL);
#include <stdio.h> // printf(), scanf()
#include <math.h> // floor()
main()
{
double grade[8];
int i;
for (i = 0; i < 8; i++)
{
do
{
printf("Insert grade: ");
scanf("%lf", &grade[i]);
grade[i] *= 10;
if (grade[i] != floor(grade[i])) // Prints error message, if user types more than one decimal point
{
printf("Grade must have one decimal point.\nPlease re-enter grade.\n");
}
}while (grade[i] != floor(grade[i])); // Checks decimal point
}
}
Use fgets() to read the line into a buffer and then test that buffer.
char buf[99];
fgets(buf, sizeof buf, stdin);
// parse the line as a float - look for problems
char *endptr;
float f = strtof(buf, &endptr);
if (buf == endptr || *endptr != '\n') Fail_NonFloatInput();
// look for .
char *dot = strchr(buf, '.');
if (dot && isdigit(dot[1]) && isdigit(dot[2])) Fail_TooMuchPrecisison();
}
Alternatively code could try:
long long i;
int f;
if (2 != scanf("%lld.%1d", &i, &f)) Bad_Input();
float fl = i + f/10.0;
But that fails float input like 123456789012345678901234567890.0.
As #Matt McNabb says, read as text first.
You can use printf format specifiers to specificy the number of positions you are interested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
Example from the cplusplus.com
#include <stdio.h>
int main()
{
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
return 0
}
Output
floats: 3.14 +3e+000 3.141600E+000
More examples here http://www.cplusplus.com/reference/cstdio/printf/

Checking input type without quitting the program and restarting it

I have a requirement to get two integers and add and print the added value. I wrote a working program. Another requirement is to check whether the input value is other than integer and if it is other than integer, without closing the program, it should again ask for the inputs.
C Code
#include <stdio.h>
void main()
{
int a,b,c;
printf("This is a Addition program");
printf("\n Enter value of a:");
scanf("%d",&a);
printf("\n Enter value of b:");
scanf("%d",&b);
c=a+b;
printf("\n The added value is %d",c);
}
Here's some code that will completely fulfil your requirement. Yesterday David C Rankin posted an answer to the same basic question in Stack Overflow.
This code is basically what David provided:
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
char c;
while(printf("%s",prompt) && scanf("%d", &value) !=1)
{
do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input
printf ("Invalid Entry, Try Again...\n");
}
return value;
}
int sum(int a , int b) { return ( a + b ); }
int main(){
int a , b;
a = getInt("Please enter a number");
b = getInt("Please enter a number");
printf("Sum is :%d" , sum(a,b));
}
The function getInt check the input and yells for the wrong input.
This program will do what you want
#include<stdio.h>
int main() //use int not void
{
int a,b,c;
printf("This is a Addition program");
printf("\n Enter value of a:");
while(scanf("%d",&a)==0)
{
printf("\n Invalid input.Try again:");
getchar(); // clear the previous input
}
printf("\n Enter value of b:");
while(scanf("%d",&b)==0)
{
printf("\n Invalid input.Try again:");
getchar(); // clear the previous input
}
c=a+b;
printf("\n The added value is %d",c);
return 0; // because main returns int
}
scanf returns the number of successfully read items, so it will return 1 in your case if a valid value was entered. If not, an invalid integer value was entered and scanf will return 0.
Use fgets()/sscanf()/strto...() rather than scanf().
scanf() parses and performs input in the same function and does not well handle unexpected input. Use fgets() for user input and then scan/parse.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
int getint(const char *prompt) {
char buf[sizeof(int) * CHAR_BIT];
while (1) {
fputs(prompt, stdout);
fflush(stdout);
if (fgets(buf, sizeof buf, stdin) == NULL) {
// sample handling of unexpected input issue.
// Value to return of EOF or IO error
return INT_MIN;
}
/// strtol() is another option
int i, n;
// " %n" notes offset of non-white-space after the numebr.
if (1 == sscanf(buf, "%d %n", &i, &n) && buf[n] == '\0') {
return i;
}
}
}
int main(void) {
int a, b, c;
printf("This is a Addition program");
a = getint("\n Enter value of a:");
b = getint("\n Enter value of b:");
c = a + b;
printf("\n The added value is %d", c);
return 0;
}

Resources