How to keep repetition out in user-defined functions - c

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.

Related

I want to convert my array values from float to double to get smaller values

When I change the type of array from float to double (float array[][] to double array[][]), it doesn't scan the values correctly. All the values become zero. For example, if I enter 5 for input when it's float, it's 5.000000. However, when it's double, every value I enter is scanned as 0.0000000.
#include <stdio.h>
#include <math.h>
int main() {
int limestone, min=0;
//for entering height of array (number of limetstone)
printf("Enter number of limestone: ");
scanf("%d", &limestone);
float array[limestone][3];
//double array[limestone][3]; (the problem)
//for getting inputs
for(int i=0;i<limestone;i++)
{
printf("Enter the %d porosity, hydraulic conductivity (m/s), specific gravity: ", i+1);
scanf("%f %f %f", &array[i][0], &array[i][1], &array[i][2] );
}
//for print array (you can remove it)
for(int i=0;i<limestone;i++)
{
for(int j=0;j<3;j++)
{
printf("%f ",array[i][j]);
}
printf("\n");
}
//Comparing 3rd (Last) Column
for(int i=limestone-1;i>=0;i--)
{
if(array[i][2]<array[min][2])
{
min=i;
}
}
printf("The limestone with the lowest specific gravity is Limestone %d with a specific gravity of %f",min+1,array[min][2]);
return 0;
}
I got your code to work by changing your scanf line to
scanf("%lf %lf %lf", &array[i][0], &array[i][1], &array[i][2] );
All I did was change the %f's to %lfs.
This works for me at least, I think it's doing what you want

My c code won't output anything whatsoever if it has a scanf(); inside of the code

#include<stdio.h>
#include <stdlib.h>
int triArea(x, y) {
int baseTimesHeight = x * y;
int area = baseTimesHeight / 2;
return area;
}
int main() {
int x = 0;
int y = 0;
printf("Enter an integer value for the length: \n");
scanf("%d", &x);
printf("Enter an integer value for the height: \n");
int area1 = triArea(x ,y);
printf("The area of the triangle is: %d\n", area1);
printf("Hello world!\n");
return 0;
}
this is the code that i wrote for a simple calculation (I am VERY new to programming in c and low level languages) however no matter the program if it has a scanf it will not output any other code. Anyone have idea as to why this happens? I'd like both a solution and explanation if possible!:)
You forgot the scanf for y:
...
printf("Enter an integer value for the height: \n");
scanf("%d", &y); // <<<<< you forgot this line
and int triArea(x, y) should be int triArea(int x, int y). Any decent compiler should issue a warning for this.
Bonus: why do you call your variable x, and y? Call them length and height instead. Code readability is very important, and correct naming of variables and functions is very important.

Why is this code not producing an output?

Im writing a simple program to show the distance/time between two converging trains. I wanted to test the program and return output value through the function float converge, and then apply that to the main function, but it seems that the converge function does not work.
#include <stdio.h>
float converge(int x, int y, int z) {
return x / (y + z);
}
int main(void) {
int dist, speed1, speed2;
printf("Enter distance in miles");
scanf("%d\n", &dist);
printf("Enter train 1 speed and train 2 speed in mph");
scanf("%d%d\n", &speed1, &speed2);
converge(dist, speed1, speed2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
float converge (float x, float y, float z)
{
int time=x/(y+z);
return time;
}
int main ()
{
float dist, speed1, speed2;
printf("Enter distance in miles:\t");
scanf("%f", &dist);
printf("Enter speed of first train in mph:\t");
scanf("%f", &speed1);
printf("Enter speed of second train in mph:\t");
scanf("%f", &speed2);
printf("Time between this two trains is %f",converge(dist, speed1, speed2));
}
There are multiple problems in your code:
converge performs integer arithmetic and converts the result to float only for the return value. If you want to compute a fractional number, you should change it to: double converge(int x, int y, int z) { return (double)x / ((double)y + z); } or better use double for the input values and the argument types:
double converge(double x, double y, double z) { return x / (y + z); }
There are trailing newlines in the scanf() conversion formats: this will cause scanf() to consume any trailing white space typed after the numbers, including any number of newlines typed at the prompts. You will not get the second prompt as long as you enter empty lines. Remove these \n from the format strings.
The result of the computation is not printed.
Here is a modified version:
#include <stdio.h>
double converge(double x, double y, double z) {
return x / (y + z);
}
int main(void) {
double dist = 0, speed1 = 0, speed2 = 0;
printf("Enter distance in miles: ");
scanf("%lf", &dist);
printf("Enter train 1 speed and train 2 speeds in mph: ");
scanf("%lf%lf", &speed1, &speed2);
if (speed1 + speed2 <= 0)
printf("No collision\n");
else
printf("Time until collision: %f seconds\", 3600 * converge(dist, speed1, speed2));
return 0;
}
Why is this code not producing an output?
It produces no output for the expected output from the result of converge() because there is no statement in the provided code, which could cause this output.
You need for example one printf() statement after the call to converge() in order to print the result of converge():
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
float converge_result;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
converge_result = converge(dist, speed1, speed2);
printf("The time until the two trains encounter each other is:\n %f",converge_result);
return 0;
}
or alternatively:
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
printf("The time until the two trains encounter each other is: \n%f ",
converge(dist,speed1,speed2);
return 0;
}
By the way, the calculation of the distance in time seems incorrect or at least incomplete.

Returning more than one variable in the same function

I just need help with returning two user input floating-point numbers using the same function. Can anyone show me how to return more then one variable? Thanks in advance.
#include <stdio.h>
#define SIDE_1_LABEL 'A'
#define SIDE_2_LABEL 'B'
float getUserValue(float side1, float side2);
int main()
{
float side1,
side2;
side1 = getUserValue(SIDE_1_LABEL);
side2 = getUserValue(SIDE_2_LABEL);
return 0;
}
float getUserValue(float side1, float side2)
{
printf(" Enter a value for Side %c.\n", SIDE_1_LABEL);
printf("> ");
scanf("%f", &side1);
printf(" Enter a value for Side %c.\n", SIDE_2_LABEL);
printf("> ");
scanf("%f", &side2);
return side1, side2;
}
You need to either put the two floats into a struct that the function can return, or pass one (or both) floats in as a pass-by-reference parameter. I would definitely prefer two pass-by-reference parameters in this case.
void getUserValue(float *side1, float *side2) {
printf(" Enter a value for Side %c.\n", SIDE_1_LABEL);
printf("> ");
scanf("%f", side1);
printf(" Enter a value for Side %c.\n", SIDE_2_LABEL);
printf("> ");
scanf("%f", side2);
}
There are other serious issues in your code, such as passing chars A and B in as the float parameters for getUserValue(), and only a single one for each call. You should call getUserValue() as:
int main() {
float side1, side2;
getUserValue(&side1, &side2);
return 0;
}
You don't need to pass in SIDE_1_LABEL and SIDE_2_LABEL, as they are #defined globally and can be accessed directly by getUserValue(). And since you get both values in a single call, you don't need to call getUserValue() twice.
Another approach would be to have getUserValue() get only a single value at a time with:
float getUserValue(char label) {
float side;
printf(" Enter a value for Side %c.\n", label);
printf("> ");
scanf("%f", &side);
return side;
}
then call it twice like you currently do :
side1 = getUserValue(SIDE_1_LABEL);
side2 = getUserValue(SIDE_2_LABEL);

User-defined Functions

I was trying to calculate the area of both a triangle and a circle using 3 separate user defined functions within main. After compiling, the GetInt function worked properly but the other two functions' calculations are not printing on the screen accurately for my c program on Microsoft Visual Studio 2013. What am i doing wrong?
#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)
{
printf("%d", GetInt());
printf("%f", CalcTriangleArea);
printf("%f", CalcCircleArea);
return(0);
}
int GetInt(void)
{
int radius, base, height;
printf("What is the radius of the circle? \n\n");
scanf("%d", &radius);
printf("What is the base of the triangle? \n\n");
scanf("%d", &base);
printf("\nthe height of the triangle? \n\n");
scanf("%d", &height);
return (radius, base, height);
}
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("Circle area is %.4f \n\n", circleArea = PI * pow(radius, 2));
return(0);
}
CalcTriangleArea Is not calling the function, it's using the functions address. Try CalcTriangleArea()
edit: Just noticed CalcTriangleArea takes parameters - you'll need to pass those in too.
edit: And how do you think you can return 3 values?
For CalcTriangleArea and CalcCircleArea there is no need to have the printf's in main if you're printing the results in your functions. You could simply call them in main like so:
GetInt();
CalcTriangleArea(base, height);
Also, if this is the approach you are taking (printing results in the function and returning 0), your functions could be declared like so:
void myFunction(int arg1, int arg2)
Since your are not returning anything that you are using, using a void type allows you to have a function without an explicit return.

Resources