How to read floating-point numbers by pairs in C? - c

Write a program that requests two floating-point numbers and prints the value of their difference divided by their product. Have the program loop through pairs of input values until the user enters nonnumeric input.
Use a function to return the value of the calculation.
I've successfully completed this exercise without using function but can't get it right using function. The program itself runs but doesn't return any value in fact it crashes.
Please any help would be appreciated.
Here is my program:
#include <stdio.h>
#include <string.h>
double result (double x, double y);
int main(void)
{
double num1, num2, res;
printf("This while calculate difference of two numbers by their product.\n");
printf("Enter first number followed by second number\n");
while (scanf("%lf %lf", &num1, &num2 ==2))
{
res= result(num1, num2);
printf("the result is equal to %.3g\n", res);
printf("Enter next set of numbers or q to quit\n");
}
return 0;
}
double result(double x, double y)
{
double output;
output = (y-x)/(x*y);
return output;
}

while (scanf("%lf %lf", &num1, &num2 ==2))
was meant to be:
while (scanf("%lf %lf", &num1, &num2) ==2)

Try changing
while (scanf("%lf %lf", &num1, &num2 ==2))
to
while (scanf("%lf %lf", &num1, &num2) ==2)

Related

scanf prevents program from running

So I wrote this program using coderunner,
#include <stdio.h>
int main()
{
int num1, num2;
scanf("%d%d", &num1, &num2);
if (num1 > num2)
printf("The min is:%d\n ", num2);
else
printf("The min is:%d\n ", num1);
return 0;
}
The problem is that the program wont run. It keeps showing this and then it stops after a while:
Removing the scanf fixed the issue, I've tried other programs using scanf and it was fine. Any ideas?
How do you expect scanf() to interpret e.g. 123 or 1232 as two integers? Chances are all digits you enter are "eaten" by the first %d, and then scanf() waits for more for the second.
You must use some separation, or some non-numeric character between them:
scanf("%d/%d", &num1, &num2);
This tells scanf() to expect a slash between the two numbers. You could just use whitespace (without any in the format string, as pointed out in comments) too of course.
Also, you should check the return value before relying on the numbers:
if(scanf("%d %d", &num1, &num2) == 2)
{
}

How do I display a message or respond towards an invalid input in C

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int a, result;
float b;
printf("**This is a simple arithmetic calculator.** \n");
printf("\n Please enter an integer: ");
scanf("%i ", a);
printf("Please enter a floating point number: ");
scanf("%f", b);
result = a + b
printf("Output: ");
printf("%i + %f = %lf \n", a, b, result);
printf("%i - %f = %lf \n", a, b, result);
printf("%i * %f = %lf \n", a, b, result);
}
I need to ensure that your program will not crash if the user enters an invalid input.
scanf is a function that has also got a return value which indicates how many inputs were inserted correctly.
So you can just do something like:
while (scanf("%i ", a) != 1)
{
printf("wrong input, try again");
}
use while loop or if for scanf
while(scanf("%i ", a) !=1){
printf("invalid input.\n");
}
and
while(scanf("%f", b) !=1){
printf("invalid input.\n");
}

Average of entered numbers in C - sum always 0

Here is a code which evaluates the average of 10 entered numbers. Problem is it doesn't seem to print the sum correctly (it's always equal to 0) after exiting the loop, everything else is working fine.
int count=0, n=10, c;
float sum=0, x;
do{
printf("x=");
scanf("%f", &x);
count++;
sum+=x;
}
while(count<n);
printf("Sum is %d", sum);
printf("\nCount is: %d", count);
printf("\nThe Average of the numbers is : %0.2f", sum/count);
getch();
}
Another question is how to exit the loop after a symbol is reached(i.e. without setting a limit to the number of integers to be entered).
Use the %f format specifier for floating point numbers.
printf("Sum is %f", sum);
To exit the loop on a symbol, you could check the return value from scanf. scanf returns the number of items read. If it returns 0 then the user didn't type a valid number.
while (1) {
printf("x=");
if (scanf("%f", &x) != 1) {
break;
}
...
}
break exits the current loop.
To answer your first question it should be printf("%f",sum) to print the correct sum. Since you are using float you have to use %f, if you use int it is %d. For your second question, you can do something like this (modify it accordingly):
int main(){
// Declare Variables
int count = 0; float sum = 0, currentNum = 0;
// Ask user for input
while(currentNum > -1)
{
printf("Enter integer to be averaged (enter -1 to get avg):");
scanf("%f",&currentNum);
if(currentNum == -1)
break;
// Check the entered number and computed sum
printf("You entered: %0.2f\n", currentNum);
sum += currentNum;
printf("Current sum: %0.2f\n", sum);
count++;
}
// Print Average
printf("Average is: %0.2f\n", sum/count);
return 0;
}
To answer your second question, you could do this:
scanf("%f", &x);
if (x==0) {
break;
}
This will break you out of the loop if you enter 0, then your loop can be infinite:
do {
} while(true)
For the second question, I think EOF may be the better solution:
while(scanf("%f", &x) != EOF)

Switch small program does not let me see result

I am learning the switch statement of C. This is my small program and it runs and does the calculation but doesn't let me see the result of the operation. The black window shows up so that I input the numbers and the operator and then for a fraction of a second shows the result and disappears. Any help is appreciated.
#include <stdio.h>
int main(int argc, char *argv[])
{
int num1, num2, ans=0;
char ch, name;
printf("Enter a value: ");
scanf("%d", &num1);
printf("Enter a second value: ");
scanf("%d", &num2);
printf("Input * To multiply\
+ To add\
- To subtract: ");
scanf(" %c", &ch);
switch(ch)
{
case'*':
ans=num1 * num2;
printf("%d times %i equals: %i",num1,num2,ans);
break;
case'+':
ans=num1+num2;
printf("%i plus %i equals: %d",num1,num2,ans);
break;
case'-':
ans=num1-num2;
printf("%d minus %d equals: %d",num1,num2,ans);
break;
default:
printf("Range numbers");
}
getchar();
return ch;
}
Probably due to output buffering. Add newlines (\n) last in your formatting strings.
As a newbie, you should end all your printf format string with an escaped newline \n, i.e. printf("%i plus %i equals %d\n", num1, num2, ans); (or you should call fflush(stdout); just after the end of the switch before the getch and before all your scanf).

What's wrong with this C program?

I've written a special calculator which prompts the user for 2 numbers then displays a menu which basicly asks the user what to do with that input. It works great however no matter what numbers I input the result is 0. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
char a, rad, patrat;
float x, y, media, radical, pat1, pat2;
patrat = 253;
rad = 251;
loop:
printf("Input 2 numbers...\n");
scanf("%f %f", &x, &y);
media = (x+y)/2;
radical = sqrt(x+y);
pat1 = x*x;
pat2 = y*y;
loop2:
printf("\n \nA - Arithmetic media.\n");
printf("B - Square root.\n");
printf("C - Sqare of the 2 numbers.\n");
printf("D - Write other numbers.\n");
printf("E - Terminate the program.\n");
a = getch();
switch(a) {
case'a':
system("cls");
printf("Media of the 2 numbers is %f", &media);
goto loop2;
case'b':
system("cls");
printf("%c%f + %f = %f", &rad, &x, &y, &radical);
goto loop2;
case'c':
system("cls");
printf("%f%c = %f, %f%c = %f", &x, &patrat, &pat1, &y, &patrat, &pat2);
goto loop2;
case'd':
goto loop;
case'e':
return 0;
}
}
You're using & in your printf statements, you shouldn't be. Scanf has it as it's writing so takes pointers.
Why are you using the operator & to your printf arguments?
printf doesn't take pointer arguments for %f conversion specification
float b;
scanf("%f", &b);
but
float a = 42;
printf("%f\n", a);
printf("Media of the 2 numbers is %f", &media);
should be
printf("Media of the 2 numbers is %f", media);
similarly for all other printf()
Generally goto statements are considered harmful when they are called backwards! So please avoid them. The same functionality can be done by a while(1) for for(;;) loop with proper termination condition.
In your printf statement, you are using
printf("Media of the 2 numbers is %f", &media);
&media is the address of your variable media.
In scanf, we provide the address of the variable as parameter so that it stores the values at that address. But in printf, we provide the variable value and not the variable address. If you provide variable address then it would print the address and not the value.
So the correction should be
printf("Media of the 2 numbers is %f", media);

Resources