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.
Related
Pls, help with the item 5 and 8 (the problem is described in the comment in code).
Here the task:
Using Euler's method to construct an approximate solution to the Cauchy problem with a given accuracy.
Write a program that calculates the approximate value of the solution to the Cauchy problem.
The initial condition (a and s (y(a)=s)) must be entered from the keyboard.
The point at which the approximate value (b) is calculated must be entered from the keyboard.
If inside or on the boundaries of the interval [a, b] the function has breakpoints (points that are not included in the Feasible region), a message should be displayed on the screen with a proposal to enter a new interval. Feasible region can be calculated manually for your specific option.
The permissible calculation error must be entered from the keyboard.
The first approximation should be calculated for n = 1. Then, when calculating each next iterative value, the number of segments should be increased in dividing the interval by 1.
It is worth stopping the iterative process if the modulus of the difference between the last two approximations is less than the specified error.
If n exceeds 10000, and the required accuracy is not achieved, display the current answer and the current error with the remark "It was not possible to achieve the specified accuracy."
The screen should display the last total value (final answer), rounded in accordance with the error, as well as the required number of iterations.
#include <math.h>
#include <stdio.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
//Here the problem item 8
//There should be a function here for
//counting decimal places in error for further rounding
//but for example I just write by myself count
int count = 1;
//Euler's method
n=1; //Here the problem item 5 (iterations always is 1)
int iter_count = 0;
while(xi<n){
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
//printf("\ny = %lf\n", y);
if (fabs(y-yi)<eps){
printf("\nDifference modulus greater than error\n");
break;
}
//printf("\nyi = %lf\n", yi);
yi=y;
//printf("\nxi = %lf\n", xi);
xi=xi+h;
n++; //Here the problem item 5
if (n>10000.0){
printf("\nIt was not possible to achieve the specified accuracy\n");
break;
}
if (y==0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(y, count));
printf("Eps is %lf\n",eps);
printf("The number of iterations is %d\n",iter_count);
}
for item5 you need the function firstdecplace()
for item8 you need two loops
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
unsigned int firstdecplace( double error ) //item 5
{
if( error <= 0 )
{
printf( "Error at firstdecplace: argument smaller equals 0\n" );
exit(1);
}
unsigned int firstdec = 0;
while( error < 1 )
{
firstdec++;
error *= 10;
}
return firstdec;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
int count = 1;
//Euler's method
int epsflag = 0;
double approx; // approximation of y(b)
int iter_count = 0;
for( n = 1; n < 10000; ++n ) // item 8 from here on
{
xi = a;
for( int iteration = 0; iteration < n; ++iteration )
{
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
if( fabs(y-yi) < eps ){
printf("\nDifference modulus smaller than error\n");
n--;
epsflag = 1;
break;
}
yi=y;
xi=xi+h;
}
if( epsflag == 1)
{
break;
}
approx = y;
if (y <= 0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
if(n == 10000){
printf("\nIt was not possible to achieve the specified accuracy\n");
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(approx, firstdecplace(eps)));
printf("Eps is %lf\n",eps);
printf( "number of iteration for the approxmation of y(b): %d\n", n );
printf("The number of total iterations: %d\n",iter_count);
}
Reference Image
The output always comes: 6.35 (I think it's a garbage value)
the code is
#include<stdio.h>
#include<math.h>
float formula(float,float);
int main()
{
float l=0,a=0;
printf("enter the length of the pendulum(l)\n");
scanf("%f",&l);
printf("Enter the angle of displacemnt(a)\n");
scanf("%f",&a);
printf("the length is %0.2f\n",l);
printf("the angle of displacemnt is %0.2f\n",a);
printf("the period of pendulum is %0.2f",formula(l,a));
return 0;
}
float formula(float l, float a)
{
float P=0,ran=0,g = 9.8;
ran = (l/g) * (1 + ((1/4)*(pow((float)(sin((double)a/2)),2))));
P = 2 * M_PI * ((float)sqrt((double)ran));
return P;
}
I don't know what is happening 😐
You can simplify this implementation by using doubles or floats exclusively. The 1/4 integer division yields 0. Here's an example:
#include <stdio.h>
#include <math.h>
float formula(float l, float a)
{
float ran = l / 9.8f * (1.0f + powf(sinf(a/2.0f), 2.0f) / 4.0f);
return 2.0f * (float) M_PI * sqrtf(ran);
}
int main(void)
{
float l;
float a;
printf("Enter the length of the pendulum(l): ");
scanf("%f", &l);
printf("Enter the angle of displacemnt(a): ");
scanf("%f", &a);
printf("The length is %0.2f\n", l);
printf("The angle of displacemnt is %0.2f\n", a);
printf("The period of pendulum is %0.2f\n", formula(l,a));
return 0;
}
I am new to the C programming language. I am attempting to run the code below an N amount of times (based on the user input of "Enter amount of iterations"). I am trying to do this using a for loop (also tried with a while loop) but have been unsuccessful.
Whenever I run the code below, my terminal continuously repeats "Enter two float numbers:". I have to close the terminal and reopen it to try again. Does the issue have to do with my for loop? I am interpreting my for loop as: "a=0; if a > 0; increment a". Is there a way I can set a limit for "if a > 0" or should I be using a while loop? If the user enters "3" for amount of iterations, I am expecting the program to ask "Enter two float numbers" 3 times (with the answer).
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
CORRECT ANSWER Formatted for readability:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
This should behave more like you would like it to:
#include <stdio.h>
static float sum(float m, float n)
{
return m + n;
}
int main(void)
{
float x, y;
int a;
printf("Enter amount of iterations: ");
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Invalid input for iterations\n");
return 1;
}
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
if (scanf("%f %f", &x, &y) != 2)
{
fprintf(stderr, "Failed to read to floating point numbers\n");
return 1;
}
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
Note that it checks that the input operations are successful, and reports errors on standard error (stderr). The code uses a standard C for loop to count from 0 up to a limit — this is idiomatic C. You should get used to using it.
As I noted in a comment, the a in the for loop is different from and unrelated to the a declared earlier in your code and set by the input operation. The a in the for loop is not initialized; you can't tell how many times the loop will be executed. A good compiler should warn you about redefining or shadowing a.
for (i = 0; i < a; i++); - answer provided by J.S!
While analyzing can't seem to avoid the value stored to 'delta' not being read... what part of my loop isn't working and why?
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c;
float delta;
printf("a=");
scanf("%f", &a);
printf("b=");
scanf("%f", &b);
printf("c=");
scanf("%f", &c);
float x, x1, x2;
delta=((b*b)-(4*a*c));
if("delta==0")
{
x=((-b)/(2*a));
printf("x=%f \n", x);
}
else if("delta>0")
{
x1=((-b+sqrt(delta))/(2*a));
x2=((-b-sqrt(delta))/(2*a));
printf("x1=%f i x2=%f \n", x1, x2);
}
else printf("Nie ma w zbiorze liczb rzeczywistych rozwiazania tego rownania.\n");
return 0;
}
1st thing, if("delta==0") inside "" whatever is present that will be treated as a address so if(address) means true, remove the double quotation.
if(delta==0)
// some code
else if (delta > 0)
// some code
2nd thing, you are comparing(==) a float & an integer, so be aware of behaviour of comparing different operands.
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.