I have written the following code
#include <stdio.h>
#include <stdlib.h>
int main()
{
// declaration of variables as strings
char astr;
char bstr;
char cstr;
/* Input three sides of a triangle */
printf("Enter first side of triangle: ");
scanf("%s",&astr);
printf("Enter second side of triangle: ");
scanf("%s",&bstr);
printf("Enter third side of triangle: ");
scanf("%s",&cstr);
// conversion of strings to float
float a = atof(&astr);
float b = atof(&bstr);
float c = atof(&cstr);
// checking if given triangle is valid
if((a + b > c) && (a + c > b) && (b + c > a))
{
// Checking for special cases of triangle
if(a==b && b==c)
{
/* If all sides are equal */
printf("Equilateral triangle.");
}
else if(a==b || a==c || b==c)
{
/* If any two sides are equal */
printf("Isosceles triangle.");
}
else
{
/* If none sides are equal */
printf("Scalene triangle.");
}
}
else
{
printf("Triangle is not valid. \n");
}
printf("%f \n", a);
printf("%f \n", b);
printf("%f \n" ,c);
return 0;
}
However when I run it, I get "Triangle is not valid" despite the fact that mathematically the triangle would be valid
When printing the Values stored in a b and c I discover that only the Value for c is stored correctly but a and b are always 0.000000
what have I done wrong?
Thanks in advance
instead of 3 wrong lines:
char astr;
scanf("%s",&astr);
float a = atof(&astr);
let me propose working lines:
char astr[20]; // should be enough
scanf("%19s",astr); // 19 protects from buffer overflow on astr
float a = atof(astr);
First, you cannot scan a string into a char: not enough room / undefined behaviour. Pass a char array instead (and in that case drop the &, it's already an address)
Second, pass the string to atof, not the pointer on the string.
Aside: atof doesn't check for errors, better use strtof which provides (optional) error checking.
int main () {
float val;
char str[10];
strcpy(str, "1234");
val = atof(str);
printf("%f", val);
return 0;
}
You can also use strtod() refer man page of atof()
Related
For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}
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?
Hello guys I started learning C few weeks ago and I am trying to make my first useful program, I am trying to create a squared equation calculator but no matter what I type in the input it always outputs "no solution2" can anyone take a look and help me ?
examples for input :
0 0 0=
1 4 1=
#include <stdio.h>
#include <math.h>
int main()
{
printf("enter a\n");
double a; scanf("%1f", &a);
printf("\nenter b\n");
double b; scanf("%1f", &b);
printf("\nenter c\n");
double c; scanf("%1f", &c);
if (a==0)
{
if (b==0)
{
if (c==0)
printf("x can be every number\n");
else
printf("no solution1\n");
}
else
{
printf("x equals %.2f\n", ((-1)*c) / b);
}
}
else
{
double delta = (b*b)-(4*(a*c));
if (delta>0)
{
double sqrtDlt = sqrt(delta);
printf("x1 = %4.2f\n", (((-1)*b) + sqrtDlt) / 2 * a);
printf("x2 = %4.2f\n", (((-1)*b) - sqrtDlt) / 2 * a);
}
else
printf("no solution2\n");
}
return 0;
}
For double use specifier %l(ell)f not %1(one)f in scanf.
Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double.
I'm fairly new to C and I have a small function which reads an input of a simple math operation (+,-,*,/) and then calculates the result accordingly and returns -nan if the input is incorrect.
float simple_math(void) {
float a, b;
int char_c;
int ret_a;
ret_a = scanf("%f %c %f", &a, &char_c, &b);
float result;
if (char_c == '+')
result = a + b;
else if (char_c == '-')
result = a - b;
else if (char_c == '*')
result = a * b;
else if (char_c == '/')
result = a / b;
else
result = 0.0 / 0.0;
return result;
}
This code works just fine. However, if I change the order of the first two lines the return value is -nan.
int char_c;
float a, b; // this was originally the first line
int ret_a;
Why does the order of the variable declarations matter?
int char_c;
should be
char char_c;
%c is used to scan character and not int so your scanf will lead to undefined behavior.
The side effect of undefined behavior is sometimes things work as expected. So please get rid of undefined behavior it has nothing to do with the ordering of variable definitions.
This is your problem:
int char_c;
ret_a = scanf("%f %c %f", &a, &char_c, &b);
You tell scanf here to read a char, but pass him an int instead. That causes scanf to read only the size of a char (1byte) instead of the size of an int (larger than bytes), so in the end, whats contained in char_c is random and definitiveley non of the four allowed characters (x-*/).
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/