Converting a Character String to a Float - c

I'm trying to take the user input, which is a character string, and convert it to a float. In my case, gas keeps being printed as 55.000000 when the user enters 7 - I'd like it to be printed as 7.0.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main()
{
char gas_gallons;
float gas;
printf("Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
while (!isdigit(gas_gallons))
{
printf("\nYou need to enter a digit. Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
}
if (isdigit(gas_gallons))
{
printf("\nHello %c", gas_gallons);
gas = gas_gallons;
printf("\nHello f", gas);
}
return 0;
}

Why not do this? It's much simpler.
#include<stdio.h>
int main()
{
int gas;
printf("Please enter the number of gallons of gasoline.\n : ");
//use the %d specifier to get an integer. This is more direct.
//It will also allow the user to order more than 9 gallons of gas.
scanf("%d", &gas);
printf("\nHello %d", gas);//prints integer value of gas
//Using the .1f allows you to get one place beyond the decimal
//so you get the .0 after the integer entered.
printf("\nHello %.1f\n", (float) gas);//print floating point
return 0;
}

You said:
In my case, gas keeps being printed as 55.000000 when the user enters 7
When the user enters 7 as input the digit 7 is stored as the character in gas_gallons. The decimal value of the character 7 is 55 in ASCII encoding. You can see the decimal values of other characters in ASCII encoding at Wikipedia and many other places on the web.
When you use:
gas = gas_gallons;
the integer value of gas_gallons is, i.e. 55, is assigned to gas. That explains why you get 55.000000 as the output when you print gas.
You can fix the problem many ways. Here are a couple of suggestions.
Option 1
Convert the digit to a number by using:
gas = gas_gallons - '0';
Option 2
Discard the code to read the number of gallons of gasoline as a digit and converting the digit to a number. Using a digit is also limiting since you cannot have 10 or 12.5 as input.
Read the number of gallons of gasoline as a number directly. With this approach, your input can be a any floating point number that can be represented by a float.
#include <stdio.h>
int main()
{
float num_gallons;
while ( 1 )
{
printf("Please enter the number of gallons of gasoline: ");
// Read the number of gallons of gas.
// If reading is successful, break of the loop.
if (scanf("%f", &num_gallons) == 1 )
{
break;
}
// There was an error.
// Read and discard the rest of the line in the input
// stream.
scanf("%*[^\n]%*c");
printf("There was an error in reading the gallons of gasoline.\n");
}
printf("\nHello %f\n", num_gallons);
return 0;
}

The ASCII-characters '0'-'9' do not have the integer values 0-9. You can find the appropriate value by subtracting '0'.

To convert a string to float you can use atof (ASCII to float) function included in stdlib.h.
Here is the full declaration of this function: double atof(const char *str)
so you can do a simple cast
gas = (float) atof(gas_gallons);

Related

i am getting a unknown error in my c program

Code:
#include <stdio.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float per;
printf("Enter subject 1 marks out of 100 \n");
scanf("%d",s1);
printf("Enter subject 2 marks out of 100\n");
scanf("%d",s2);
printf("Enter subject 3 marks out of 100 \n");
scanf("%d",s3);
printf("Enter subject 4 marks out of 100\n");
scanf("%d",s4);
printf("Enter subject 5 marks out of 100\n");
scanf("%d",s5);
sum=s1+s2+s3+s4+s5;
per=sum/100;
if (per>60 && per<70){
printf("your percentage is %d and you get 10% schoolarship",per)
;}
else if (per>70.1 && per<90){
printf("your percentage is %d and you get 20% schoolarship",per)
;}
else {
printf("your percentage is %d and you get 30% schoolarship",per)
;}
}
Output:
I am trying to make a percentage calculator and it shows a weird output.
What am I doing wrong?
When you call scanf, it is important to pass in the address of the variable you want to store. Otherwise, scanf will not behave as you expect.
Right now, you are not passing in the address to scanf; but rather the variable itself.
So you should do something like:
scanf("%d",&s1);
instead.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I recommend reading a little bit about how scanf works at the following link.
"Following is the declaration for scanf() function.
int scanf(const char *format, ...)"
Additionally, check out this link for a few examples of scanf:
https://www.programiz.com/c-programming/c-input-output
scanf("%d", &testInteger);
The syntax is format first, then pass in the address of where you want to store the data.
scanf() requires a pointer to the value, it should be scanf("%d",&s1);

How can I get rid of zeros, if decimal is entered it prints decimal, but if whole number is entered it prints .00?

This program prints overlapping of two intervals. But the problem is, if I enter, for example numbers :
1.1 -1.1 1.1 1.1, it prints out the whole number. I've tried writing %1.1f in last printf command, but it turned out to be even worse, because then, if I enter 1 2 1 1, it prints out 1.0 and 4.0. How can I get the proper print if I enter decimale or int?
#include <math.h>
int main() {
float a,b,c,x,derivative;
printf("Input coefficients a, b i c: ");
scanf("%f %f %f",&a,&b,&c);
if((a<(-10)) || (a>10) || (b<(-10)) || (b>10) || (c<(-10)) || (c>10)){
printf("Coefficients a, b i c do not belong in range of (-10,10).");
return 1;
}
printf("Input point x: ");
scanf("%f",&x);
derivative=(2*a*x)+b+(c*0);
printf("First derivation in point x=%.f je %.f.",x,derivative);
return 0;
}
You can use the "%g" format specifier to display floating-point numbers in the shortest possible way:
printf("First derivation in point x=%g je %g",x,derivative);

C Programming - Average

Okay I'm entirely stuck here and I do apologise if this inconviences you guys in any way but I need your help.
I'm currently learning C by myself and slowly getting there, started yesterday. So I thought I would give myself a task on having the user input 3 numbers and the program would have to find the average number between those three.
Here is my code:
#include <stdio.h>
int main() {
int firstnum, secnum, thirnum, finalnum;
printf("Enter the first number \n");
scanf("%f",&firstnum);
printf("Enter the second number \n");
scanf("%s",&secnum);
printf("Enter the third number \n");
scanf("%t",&thirnum);
finalnum = (firstnum +secnum+thirnum)/3;
printf("The average value is: " finalnum);
return finalnum;
}
Reading integers or floats: Correct format specifier
For integers you'll need %dand for doubles %lf. Read more about those elsewhere.
E.g.
scanf("%d",&firstnum);
Printing integers or floats
E.g.
printf("The average value is: %d", finalnum);
Avoid integer division: casting or all floats
See http://mathworld.wolfram.com/IntegerDivision.html
E.g.
double finalnum = (firstnum +secnum+thirnum)/3.0;
Or use floats for all types.
double firstnum, secnum, thirnum, finalnum;
Return 0 for success in main
return 0;
I found the fix linking with the comments made by harre and Klas Lindbäck. Thank you both.
I changed my format specifiers to %d as suggested. I then changed my printf line a little bit more.
I then tried to make a float with my int > finalnum but it didn't work. All this did was continously return the average as '0' so I placed finalnum back as an int. This is how the code looks now:
#include <stdio.h>
int main() {
int firstnum, secnum, thirnum;
int finalnum;
printf("Enter the first number \n");
scanf("%d",&firstnum);
printf("Enter the second number \n");
scanf("%d",&secnum);
printf("Enter the third number \n");
scanf("%d",&thirnum);
finalnum = (firstnum + secnum + thirnum)/3;
printf("The average value is: %d", finalnum);
return finalnum;
}
Thank you all :)
Use float instead of int to get decimal precision
otherwise the finalnum would get rounded off
use this for printing float
printf("The average value is: %f",finalnum);
for more on printf you can refer this link
http://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

Validating input with isdigit for a factorial program

I wrote the following code in C to make a program which calculate the factorial of any number.
I want to add to my program some validation/error handling, such as preventing random characters, floats or negative values from being entered, so I used the isdigit function.
Unfortunately there is a hidden problem which I don't know how to solve. When I enter any input it considers it to be false (i.e. not a digit) even if it's a positive digit.
#include <stdio.h>
#include <ctype.h>
int main()
{
char choice;
unsigned long long int factorial=1;
int counter,number;
for(;;)
{
printf("Please , enter a positive integer number only : ");
scanf("%d",&number);
fflush(stdin);
if(isdigit(number))
{
for(counter=number;counter>1;counter--)
factorial*=counter;
printf("The factorial of number %d is %llu",number,factorial);
}
else
{
printf("\a\aError\n");
continue;
}
printf("\n1-Press c or C if you want to calculate the factorial of a new number\n2-Press any key if you want to exit the program\n ");
scanf("%c",&choice);
if(choice=='c'||choice=='C')
{
factorial=1;
system("cls");
continue;
}
else
return 0;
}
}
You are using isdigit wrong. Read its documentation to find out what it actually does.
You probably meant:
if ( number >= 0 && number <= 9 )
However you also need to check whether scanf succeeded or not. If they type in some words, then scanf("%d" fails and does not update number, so trying to access number in that case accesses an uninitialized variable. To deal with that you could either check the return value of scanf, or do:
int number = -1;
scanf("%d",&number);
because the value will be left unchanged if the input failed.
NB. Don't use fflush(stdin)
isdigit checks a single character if that's a decimal digit character.
But, your input could be say 25, multiple characters. So, I changed a portion:L
char input[30];
for(;;)
{
printf("Please , enter a positive integer number only : ");
scanf("%s",input);
if(isdigit(input[0]))
{
number = atoi(input);
for(counter=number;counter>1;counter--)
Keeping rest of your program snippet same.
Here, isdigit is used to check if the first character in input is a digit and therefore a valid candidate to be converted by atoi into an integer value number.

How to print the smallest number from a set of inputted integer?

I want to write a program where it prompts people to enter a set of integers separated by a space. The user should be able to enter any amount of integer. It will find the two smallest integer in the set and print it out. Printing the smallest number and then printing the second smallest. My question is how do I get the value of min1 to be the first integer they enter, other than a static one? When I did a test run all it printed was a space, why is that? Here is what I have so far:
Update:
I'm now trying this approach, but it just freeze after I enter an input such as 76 5 74 2.
#include <stdio.h>
int min1, min2;
int input;
int main(){
printf("Please enter some integer: ");
scanf("%d", &min1);
while(scanf("%d", &input) != 0){
min1=input;
}
printf("%d", min1);
return 0;
}
You should add \n in the end of the first printf, so it will not buffered.
Also, be care that you work with digits - not integers.
and for your question - just write min1=getchar();.
EDIT: some code that may do what that you want:
printf("Enter numbers. (other chars to end)\n");
int min,input;
scanf("%d",&min);
while (scanf("%d",&input))
if (input<min)
min=input;
printf("min: %d\n",min);
Maybe you need scanf("%d", &number); to read integers.
For your question, just call scanf to read the first number, or set up a flag to indicate if it's the first input.
Why did you got a space printed? Because %c prints characters not numbers, try %d.
But even after that you won't get the answer you are looking for. getchar() gets a character (go figure...) from the user input, and you are storing that character into a numeric value, for single digit numbers it would magically work since even as characters '9' > '8' > '7' > ... > '0', but you'll get the ascii value of the smallest number printed at the end.
You need two things:
Some way for the user to tell your program they are done entering numbers, so some kind of conditional statement
Some way to compare the numbers they have entered so another conditional statement comparing numbers
In sudocode, maybe something like:
while (user still wants to give numbers):
number = get user input
if number does not equal exit_case:
if number < current minimum number:
current minimum number = number
else:
break out of the while loop
print current minimum number
{
int a,b=1,min;
printf("Enter Number\n");
scanf("%d",&min);
while(b<10)
{
scanf("%d",&a);
if(min>a)
{
min=a;
}
b++;
}
printf("Smallest Num ::%d",min);
}

Resources