How i can handle garbage? - c

I am novice to C. I am trying to write a program to calculate the Hypotenuse, but when I run it I get garbage values and I don't know how to handle it.
double Hypotenuse(double base, double perpendicular)
{
double hyp = sqrt((base*base) + (perpendicular*perpendicular));
return hyp;
}
int _tmain(void)
{
double b, p;
printf("Enter the lenght of base\n");
scanf_s("%f",&b);
printf("Enter the lenght of perpendicular\n");
scanf_s("%f",&p);
printf("The hypotenuse of the triangle is %3.3f",Hypotenuse(b,p));
return 0;
}

problem is in your scanf statements.
As a thumb rule you should always use "%lf" for doubles.
This works perfectly:
double Hypotenuse(double base, double perpendicular)
{
double hyp = sqrt((base*base) + (perpendicular*perpendicular));
return hyp;
}
int _tmain(void)
{
double b, p;
printf("Enter the lenght of base\n");
scanf_s("%lf",&b);
printf("Enter the lenght of perpendicular\n");
scanf_s("%lf",&p);
printf("The hypotenuse of the triangle is %3.3lf",Hypotenuse(b,p));
return 0;
}

So, the best way to see what is going on in your code or where u get garbage, after all scanf print the value
ex:
double a;
scanf("%f",&a);
printf("a=%f",a); //OR
printf("a=%3.3f",a);
and you can easy see if the problem is in your scanf or somewhere else..

Related

Function to evaluate exponent

I wrote the following code in c to evaluate exponent of a number without using the math library
#include <stdio.h>
float powr(float,int);
int main(){
float a;
int b;
printf("Enter base and exponent a^b: ");
scanf("%.2f %d",&a,&b);
float p=powr(a,b);
printf("%.2f",p);
return 0;
}
float powr(float x,int y){
float r=1;
for(int i=1;i<=y;i++){
r=r*x;
}
return(r);
}
but no matter what base and exponent I input, the ouput always comes out to be 1.00. I can't find any mistake in this program and I tried running the powr function algorithm inside main() in a seperate program and it works.
In scanf() it onlys accepts field-width format, but no precision, see here.
You can just input the value, like this:
scanf("%f %d",&a,&b);
Also, you should always check the return value of scanf(). Something like this:
numOfItems = scanf("%.2f %d",&a,&b);
if(numOfItems != 2) // uh-oh
{
printf("Error while input!");
}

Infinite Recursion loop C

We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}

Returns a value as an output parameter

I have a question in C where I need to insert coefficients of a quadratic equation into a function and return the number of solutions and result.
Write a program that accepts a series of 3 real numbers, which are the
coefficients of a quadratic equation, and the program will print out
some solutions to the equation and the solutions themselves.
Guidelines:
Functions must be worked with one of the functions that
returns the number of solutions as a returned value, and returns the
solutions themselves through output parameters.
3 numbers must be
received each time. The input will be from a file (will end in EOF)
In the meantime I built the function without reading from a file just to see that it works for me, I built the function that returns the number of solutions but I got entangled in how to return the result as output parameter
here is my code for now:
int main ()
{
double a, b, c, root1,root2,rootnum;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
rootnum=(rootnumber(a,b,c);
printf("the number of roots for this equation is %d ",rootnum);
}
int rootnumber (double a,double b, double c)
{
formula=b*b - 4*a*c;
if (formula<0)
return 0;
if (formula==0)
return 1;
else
return 2;
}
In C, providing an "output parameter" usually amounts to providing an argument that is a pointer. The function dereferences that pointer and writes the result. For example;
int some_func(double x, double *y)
{
*y = 2*x;
return 1;
}
The caller must generally provide an address (e.g. of a variable) that will receive the result. For example;
int main()
{
double result;
if (some_func(2.0, &result) == 1)
printf("%lf\n", result);
else
printf("Uh oh!\n");
return 0;
}
I've deliberately provided an example that illustrates what an "output parameter" is, but has not relationship to the code you actually need to write. For your problem, you will need to provide two (i.e. a total of five arguments, three that you are providing already, and another two pointers that are used to return values to the caller).
Since this is a homework exercise, I won't explain WHAT values your function needs to return via output parameters. After all, that is part of the exercise, and the purpose is for you to learn by working that out.
Apart from a wayward parenthesis in the call and some other syntax errors, what you have so far looks fine. To print out the number of roots, you need to put a format specifier and an argument in your printf statement:
printf("the number of roots for this equation is %d\n", rootNum);
The %d is the format specifier for an int.
Here is your working code:
#include <stdio.h>
int rootnumber (double a,double b, double c)
{
double formula = (b*b) - (4*(a)*(c));
if (formula > 0) {
return 2;
}
else if (formula < 0) {
return 0;
}
else {
return 1;
}
}
int main (void)
{
double a, b, c;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
printf("The number of roots for this equation is %d ", rootnumber(a,b,c));
return 0;
}
It just need some sanity checking, its working now:
#include<stdio.h>
int rootnumber(double a, double b, double c);
int main ()
{
double a, b, c, root1,root2;
int rootnum;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
rootnum=rootnumber(a,b,c);
printf("the number of roots for this equation is %d", rootnum);
return 0;
}
int rootnumber(double a, double b, double c)
{
int formula= (b*b) - (4*a*c);
if (formula<0)
return 0;
if (formula==0)
return 1;
else
return 2;
}

Double Exponent from user input

So my question relates to double, I am trying to get an input from the user in decimal point for any value and its exponent also in decimal point to display the result after calculation in another function where the variables will pass values as double and I have used double the output as well but the end result is 1.00000 even though I have used the output specifier as %lf%.
#include <stdio.h>
double pwra (double, double);
int main()
{
double number, power, xx;
printf("Enter Number: ");
scanf("%lf", &number);
printf("Enter Number: ");
scanf("%lf", &power);
xx=pwra (number,power);
printf("Result: %lf", xx);
return 0;
}
double pwra (double num, double pwr)
{
int count;
int result = 1;
for(count=1;count<=pwr;count++)
{
result = result*num;
}
return result;
}
You have used the wrong type for result in the pwrs() function.
Change:
int result = 1;
to:
double result = 1.0;
Note that this type of simple mistake is easily identified if you learn to use your debugger. Further reading: How to debug small programs.
Also note that pwr should be an int, not a double, since your function only works with integer exponents.

How to keep repetition out in user-defined functions

After compiling, my GetInt function causes the printf statements within the function to be printed on the screen three times. I believe this was caused when I initialized all radius, base, and height to GetInt(void) but I see no other way of accurately initializing those variables. Please help!
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159
#include <stdio.h>
#include <math.h>
int GetInt(void);
double CalcTriangleArea(int base, int height);
double CalcCircleArea(int radius);
int main(void)
{
int radius, base, height;
double triangleArea;
double circleArea;
radius = GetInt();
base = GetInt();
height = GetInt();
triangleArea = CalcTriangleArea(base, height);
circleArea = CalcCircleArea(radius);
return(0);
}
int GetInt(void)
{
int x;
{
printf("Please enter a radius: \n\n");
scanf("%d", &x);
printf("Please enter a base: \n\n");
scanf("%d", &x);
printf("Please enter a height: \n\n");
scanf("%d", &x);
}
return(x);
}
double CalcTriangleArea(int base, int height)
{
double triangleArea;
printf("Triangle area is %.2f \n\n", triangleArea = .5*base*height);
return(0);
}
double CalcCircleArea(int radius)
{
double circleArea;
printf("Area is %.4f \n\n", radius, circleArea = PI * pow(radius, 2));
return(0);
}
A rule of thumb is to avoid repeating yourself whereever possible and don't repeat yourself. Imagine you want to change from two new lines (\n\n) to three (\n\n\n)? You would need to make that change three times.
Looking at the bare bones of GetInt, you are printing a prompt, two new lines, get a value and returning it. Thus, we can write the new function like this:
void getInt(char* prompt)
{
int x, numberOfConversions; // numConversions is the number of int's read from the keyboard buffer
printf("%s: \n\n", prompt);
numberOfConversions = scanf("%d", &x);
while (numberOfConversions != 1) // while the user did not enter a number
{
printf("Please enter a number: ");
numberOfConversions = scanf("%d", &x)"
}
return x; // Always returns a valid number
}
GetInt asks for, and reads, 3 distinct values, yet returns only the last one, every time it is called.
I think what you really want is to have GetInt ask for and return just 1 value, either passing it the prompt to print or printing it before calling it.

Resources