Issue generating program output to .txt file - c

I am currently enrolled in college and taking a programming course. The program seems to function correctly, however in order to submit my lab I need to provide the output via .txt file. When I go to find the file, it comes up blank. I am very new to coding and would appreciate any help in the simplest form of understanding. I have attached my program below. I am referencing my books "Focus on Fundamentals of Programming with C" and "Problem Solving and Program Design in C"
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define SECS_PER_HOUR 3600 //1 hour = 60 minutes in an hour * 60 seconds in a minute =
3600 seconds in 1 hour
#define METERS_PER_MILE 1600
FILE *fp;
int main()
{
double distance, time, speed_mph, speed_mps;
fopen_s(&fp, "csis.txt", "w");
scanf("%lf", &distance);
scanf("%lf", &time);
speed_mph = distance / time;
speed_mps = (speed_mph * METERS_PER_MILE) / SECS_PER_HOUR;
printf("\nThe speed is %.2f miles per hour. \n", speed_mph);
printf(fp, "\nThe speed is %.2f miles per hour. \n", speed_mph);
printf("The speed is %.2f meters per second.", speed_mps);
printf(fp, "The speed is %.2f meters per second.", speed_mps);
fclose(fp);
return 0;
}

Use fprintf to write to the file.
printf("\nThe speed is %.2f miles per hour. \n", speed_mph);
fprintf(fp, "\nThe speed is %.2f miles per hour. \n", speed_mph);
printf("The speed is %.2f meters per second.", speed_mps);
fprintf(fp, "The speed is %.2f meters per second.", speed_mps);

Related

Shipping calculator not returning correct results

The assignment is to write a shipping calculator using the following information.
Packages above 50 pounds will not be shipped. You need to write a program in C that calculates the shipping charge.
The shipping rates are based on per 500 miles shipped. They are not pro-rated, i.e., 600 miles is the same rate as 900 miles or 1000 miles.
Here are the shipping charges -
Package Weight Rate per 500 miles shipped
Less than or equal to 10 pounds $3.00
More than 10 pounds but less than or equal to 50 pounds $5.00
If the shipping distance is more than 1000 miles, there is an additional charge of $10 per package shipped.
I originally started writing the program using double but wanted to used a trick I had seen on here to always force the program to round up for the shipping charges by adding 499 to distance then dividing by 500.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Shipping, packageWeight, packageDistance, packagePrice;
printf("Enter the weight of the package: \n");
scanf("%d", &packageWeight);
printf("The weight you have entered is %.2d\n", packageWeight);
if (packageWeight <= 10 )
Shipping = 3.00;
if (packageWeight <= 50 && packageWeight > 10 )
Shipping = 5.00;
if (packageWeight > 50.0) {
puts("Sorry, we only ship packages of 50 pounds or less.");
return 0;
}
printf("How far are you sending the package? \n");
scanf("%d", &packageDistance);
printf("The distance you entered is %.2d\n", packageDistance);
if (packageDistance <= 1000){
packagePrice = (packageDistance + 499 / 500) * Shipping;
printf("The shipping charge is %.2d \n", packagePrice);
system("pause");
}
if (packageDistance > 1000) {
packagePrice = (packageDistance + 499 / 500) * Shipping + 10.00;
printf("The shipping charge is %.2d \n", packagePrice);
system("PAUSE");
}
}
With a weight of 10 and distance of 501 the output should be a shipping charge of 6 but was 1503
Based on a a weight of 20 and a distance of 1001 the program should output a shipping charge of 25 but was 5000
You have mess with integers / doubles, output, expressions, etc.
Let me show you why you get 1503:
if (packageDistance <= 1000){
packagePrice = (packageDistance + 499 / 500) * Shipping;
printf("The shipping charge is %.2d \n", packagePrice);
system("pause");
}
Your packageDistance is 501 then if statement is true and you get inside.
Then you setup package price. First you get packageDistance which is 501. Then you add it with 499/500 which is 0 since 499 < 500 and you attempt to get integer part of division (as per C/C++ standard). The sum of 501 and 0 is 501.
Now, you multiply it with Shipping. The value you set is 3.0, but smart C convert it to integer 3. 501 * 3 is 1503 and you get the result.
Finally, you try to sent output as %.2d. This is nonsense and I am surprised C shows something at all, but I believe it just see d and ignores .2
This is what you have to do:
Understand your business logic (you do)
Be careful with integers and floating point numbers, read C documentation or send questions here if you do not understand something.
Make sure you use brackets when needed: a + b / c is not the same as (a + b) / c
Make sure you do not use integer division if you mean to use "regular" division.
Make sure you use %d for integers and %.2f for floating point numbers when appropriate.

Code is ignoring IF command in C, Issues with FOR

I had posted on here before, but I was never able to get the help I needed.
I'm working on a school project and I can not get my program to work properly.
The program should prompt the user to enter the number of gallons used and
the number of miles driven for each of the 3 tanks of gas. The program should
then calculate and display the miles per gallon obtained for each tank. Once
processing is complete for the 3 tanks, the program will calculate the overall
mileage(total gallons / total miles) and display a friendly "Goodbye" message.
The issue i am having is that I can not get it to display to OVERALL Millage. it ends after looping 3 times.
I know different loop statements need conditions to be met, but I cant get the FOR loop to work properly. Im getting really frustrated, cause I know this should not be this hard.
Code
#include <stdio.h>
int main(void)
{
int miles,i=3;
float gallons, mg, overall = 0, avg = 0;
while(i>0)
{
printf("Enter the gallons used: ");
scanf("%f", &gallons);
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;i--;
}
if(gallons == 0)
{
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
return 0;
}
If I read your code correctly, then what is preventing the overall mileage from being printed is the following final if statement:
if (gallons == 0)
If you remove it, then the overall mileage should print. Use this pattern:
while (i > 0)
{
// your while loop here
}
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
This if (if (gallons == 0) {})block is out of while loop.
First, you need to move the if loop inside while loop.
and this if condition should be for variable i as follow and not for gallons.
if (i == 0)
{
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
}
In this case, after 3 iteration, value of i will be 0 so it will enter into the if block and calculate and print the overall miles/gallon.
Adding to Tim Biegeleisen's answer:
mg = miles/gallons;
What if gallons equals to 0? e.g. 0 miles for 0 gallons
This will lead to floating point exception.
A simple if-else can solve this problem!
if(!gallons)
mg = 0;
else
mg = miles/gallons;

Invalid operands to binary & (have 'float *' and 'float')

I can't figure out what I need to do to get my code to work, I've tried a few things but the same error keeps occurring. I'm not sure how else to proceed, the main issue of the code appears to be converting the hours and minutes into only hours. I know this is a very basic question, but I'm a beginner and I can't seem to get a solution.
// freezer.c
// Estimates the temperature in a freezer given the elapsed time since a power failure.
#include <stdio.h>
#include <math.h>
int main(void) {
float dec_time, // input - time in hours and minutes.
temperature, // output - temperature in degrees celsius
hours, // input for dec_time
minutes; // input for dec_time
/* Get the time in hours and minutes */
printf("hours and minutes since power failure: ");
scanf("%lf%lf", &hours &minutes);
/* Convert the time in hours and minutes into only hours in real number */
dec_time = hours + (minutes / 60.0);
// Using time via an equation to estimate the temperature
temperature = ((4 * dec_time * dec_time) / (dec_time + 2)) - 20;
// Display the temperature in degrees celsius
printf("Temperature in freezer %9.2f.\n", temperature);
return 0;
}
Any explanation anyone can give to give me insight on this would be greatly appreciated.
Edit: when I added the comma to the scanf() statement in the code on my computer, the primary compilation error in the title was resolved. I also changed the %lf to %f, but now when I key in a single digit to a.out, e.g. 3, the program does not compute until I key in q!.
Change scanf("%lf%lf", &hours &minutes) to scanf("%f%f", &hours, &minutes). No 'l', #melpomene add comma #Anton Malyshev.
Also recommend to check result to see if it is 2. (2 fields successfully scanned).
if (2 != scanf("%f%f", &hours, &minutes)) {
puts("Input error");
exit(1);
}
scanf("%lf%lf", &hours &minutes);
^ comma needed
You missed a comma ,.
Re-write as follows-
scanf("%f%f",&hours,&minutes); // make sure you use only %f and not %lf
You missed comma, that's how it should be: scanf("%lf%lf", &hours, &minutes)

The output of ceil() and floor() in C language is odd

I am doing my homework to realize a C programe and during my work there is one step that I need to get the interger part of the double type numbers. So I choose ceil() or floor() in to realize this. But the output is unpredictable and far from expected.
The whole program is the following :
/*
************************************************************************
Includes
************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <time.h>
#include <math.h>
/* Solvent Particle Propersities*/
typedef struct
{
double vx,vy,rx,ry ; /* velocity AND position */
double cell; /* index of grid */
}solvent_p;
/* Cell Propersities*/
typedef struct
{
double vcm_x,vcm_y ; /* center of mass velocity */
int number; /* number of solvent in the cell */
double roation_angle; /* roation_angle of the cell */
}cell_p;
/* periodic boundary condition judging and adjusting fuction PBC */
void PBC(solvent_p *sol)
{
double L = 20.0; // box size 20
if(sol->rx >20) sol->rx=sol->rx-L;
if(sol->rx < 0) sol->rx=sol->rx+L;
if(sol->ry >20) sol->ry=sol->ry-L;
if(sol->ry < 0) sol->ry=sol->ry+L;
}
int main(int argc, char **argv)
{
// Randome setup generates random numbers from GSL functions
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
gsl_rng_default_seed = ((unsigned long)(time(NULL))); //设seed值为当前时间
r = gsl_rng_alloc (T);
solvent_p solvent[4000];
int i,j,k,index=0;
cell_p grid[400];
double alpha=90.0; //roation angle
/* Iniinitializing solvent
* All vx=0
* half vy = sqrt(3) and half vy=-sqrt(3) to make momentum zero and another requirement is the overall energy is 6000 equals energy of temperature=1 with 4000 solvent 3NkT/2 ,assuming mass of solvent = 1 ,which is all a test quantity
* rx and ry are random number generated by GSL library
* cell=20*(ry+rx) is an index of which cell the solvent is in
*/
for(i=0;i<=3999;i++)
{
solvent[i].vx=0.0;
if(i<=1999)
solvent[i].vy=sqrt(3);
else
solvent[i].vy=-sqrt(3);
solvent[i].rx =20.0 * gsl_rng_uniform_pos(r);
solvent[i].ry =20.0 * gsl_rng_uniform_pos(r);
//printf("%f \t %f \n",solvent[i].rx,solvent[i].ry);
solvent[i].cell=20*(floor(solvent[i].ry))+floor(solvent[i].rx)+1;
}
// grid setting up
for (i=0;i<=399;i++)
{
grid[i].vcm_x=0;
grid[i].vcm_y=0;
grid[i].number=0;
grid[i].roation_angle=0.0;
}
/* Begining Simulation Work
*
* Fist process is preparing the system to equilibrium for 10000 processes
*
* the whole process involving two steps steaming and collision and the two steps are conducted one by one in our simulation
* time duration for steaming is 0.1 which is assigned for Molecular Dynamics and time duration for collision is ignored
*
*
*/
for(i=0;i<=9999;i++)
{
double temp;
double delta_t_MD=0.1; //time step
temp=gsl_rng_uniform_pos(r);
double rand_rx = (temp < 0.5) ? temp : ((-1) * temp ); // randomshift rx;
temp=gsl_rng_uniform_pos(r);
double rand_ry = (temp < 0.5) ? temp : ((-1) * temp ); // randomshift ry
//steaming
for(j=0;j<=3999;j++)
{
//printf("%d \n",j);
printf("1 :%d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
solvent[j].rx=solvent[j].rx+solvent[j].vx * delta_t_MD;
solvent[j].ry=solvent[j].ry+solvent[j].vy * delta_t_MD;
printf("2: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
//randomshift
solvent[j].rx=solvent[j].rx+rand_rx;
solvent[j].ry=solvent[j].ry+rand_ry;
printf("3: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
// periodic boundary condition
PBC(&solvent[j]);
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
solvent[j].cell=20*(ceil(solvent[j].ry)-1)+ceil(solvent[j].rx);
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry,ceil(solvent[j].rx),ceil(solvent[j].ry));
index = (int)(solvent[j].cell);
//printf("%d \t %d \t %f \t %f \t %f \n",j,index,solvent[j].cell,ceil(solvent[j].rx),ceil(solvent[j].ry));
if ((index>=0) &&(index<=400))
{
grid[index].vcm_x=grid[index].vcm_x+solvent[i].vx;
grid[index].vcm_y=grid[index].vcm_y+solvent[i].vy;
grid[index].number=grid[index].number+1;
}
}
// caculating vcm
for (k=0;k<=399;k++)
{
if (grid[k].number >= 1)
{
grid[k].vcm_x=grid[k].vcm_x/grid[k].number;
grid[k].vcm_y=grid[k].vcm_y/grid[k].number;
}
double temp;
temp=gsl_rng_uniform_pos(r);
grid[k].roation_angle = (temp < 0.5) ? alpha : ((-1) * alpha );
}
//collsion
}
gsl_rng_free (r); // free RNG
return 0;
}
Sorry it is some extent long so I did not put in first.And something did not finished but the program framework is set up.
my programe is like this:
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
solvent[j].cell=20*(floor(solvent[j].ry))+floor(solvent[j].rx)+1;
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,floor(solvent[j].rx),floor(solvent[j].ry));
And although something as I wanted something more is wrong and below is I choose some parts of the output:
4: 3993 3.851240 17.047031
5: 3993 3.851240 17.047031 3.000000 9.000000
although floor(solvent[j].rx) is right but floor(solvent[j].ry) is totally wrong.
And the final result of my program is
Segmentation fault (core dumped)
------------------
(program exited with code: 139)
How to fix this one? Is there anything I use was wrong?
And to further test the problem I tried ceil() function in and the program and result is like this
program:
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
solvent[j].cell=20*(ceil(solvent[j].ry)-1)+ceil(solvent[j].rx);
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,ceil(solvent[j].rx),ceil(solvent[j].ry));
result:
2: 3999 14.571205 2.837654
4: 3999 14.571205 2.837654
5: 3999 14.571205 2.837654 15.000000 15.000000
So use the nearest output as an example to illustrate my desire result is:
a= 14.571205, ceil(a)=15.00
b= 2.837654 , ceil(b)=3.00 not the 15.000 in the output
And the problem worsening is that when I just use a and b to test ceil() everything seems perfect:
program:
#include <stdio.h>
#include <math.h>
int main()
{
double a= 14.571205;
double b= 2.837654 ;
printf("%f \t %f \n",ceil(a),ceil(b));
return 0;
}
output:
15.000000 3.000000
I am using GCC in Linux Ubuntu.
==============================================================================
The problem has been solved.
The real fatal problem is here
if ((index>=0) &&(index<=400))
{
grid[index].vcm_x=grid[index].vcm_x+solvent[i].vx;
grid[index].vcm_y=grid[index].vcm_y+solvent[i].vy;
grid[index].number=grid[index].number+1;
}
}
Both solvent[i].vy and solvent[i].vx should be changed i for j.
Just as #Jon and #Blckknght #Eric Lippert have pointed out.
And I obvious get in the wrong trap and mislead #ouah and #Blckknght and In fact, the output sentences do have problem but they do not caused the prorame to crash only the out of boundary will do that.
Thank you ALL!
And I do like to share Eric Lippert 's comment which is powerful and insightful:
More generally, the problem you have is called "select isn't broken" by experienced programmers. That is, you have done something completely wrong, you cannot figure out what you did wrong, and so you conclude that a piece of basic, easy infrastructure written by experts and tested extensively is wrong. I assure you, floor and ceil do exactly what they are supposed to do. They are not wrong. The problem lies somewhere in your code, not in the standard library. – Eric Lippert
Your array is declared as:
solvent_p solvent[4000];
but you have this loop:
for(i=0;i<=9999;i++)
with this function call inside:
printf("1 :%d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
which means you are accessing out-of-bounds array elements.
EDIT:
OP test case has been edited to fix the out-of-bound accesses.
My second suggestion is to check index value (which is used to index grid array) never exceeds the number of elements of grid array after this assignment: index = (int)(solvent[j].cell).
I'm pretty sure the issue is with the indexes you're using. In the statement in question:
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,floor(solvent[j].rx),floor(solvent[j].ry));
you are printing the ry value of solvent[i] but the floor of the ry value of solvent[j]. I suspect that you want to be using the same index in both places (though I'm not sure which index you want).

remove trailing zeros from output

So my program works and compiles it does what I ask.
But my program's output has these trailing zeros that I would like to eliminate.
It's not like it bothers me but I definitely would like to have it cleaned up a little.
If anyone could give me a little insight on how to eliminate the trailing zeros your help,
would be greatly appreciated.
#include "stdafx.h"
#include "stdio.h"
#define BPR 10 // Basic Pay Rate is $10.00/hr.
#define OTPR 15 // Over Time is time and a half.
#define OT 40 // Overtime is after 40 hours.
#define RATE1 .15 // Tax Rate 15%.
#define RATE2 .20 // Tax Rate 20%.
#define RATE3 .25 // Tax Rate 25%.
#define LIMIT1 300.00 // The first 300.00.
#define LIMIT2 200.00 // 200 after the first 300.
int main(void)
{
int hours;
double tax;
double gross;
double taxes1=0,taxes2=0,taxes3=0;
double net;
double hold1=0,hold2=0,hold3=0;
printf("Please enter hours worked: ");
scanf_s("%i", &hours);
if(hours < OT)
gross=hours*BPR;
else
gross=((hours-OT)*OTPR+(OT*BPR));
if(gross > LIMIT2 && gross < LIMIT1)
taxes1=gross*RATE2, hold1=gross-taxes1;
if(gross > LIMIT1)
taxes2=gross*RATE1, hold2=gross-taxes2;
if(gross < LIMIT2)
taxes3=gross*RATE3, hold3=gross-taxes3;
if(gross > 0)
{
net=(hold1+hold2+hold3);
tax=(taxes1+taxes2+taxes3);
}
printf("Your Net Pay is %f\n", net);
printf("Your Gross Pay was %f\n", gross);
printf("Your Taxes paid are %f\n", tax);
return 0;
}
if 65 was put in for the hours variable the output would read:
Your Net pay is 828.750000
Your Gross Pay was 975.000000
Your Taxes paid are 146.250000
as you can see there are a lot of zeros I would love to have disappear please help ?
Use %.2f as the output format.
You can specify how many positions you want to display after the decimal point using . followed by the number of positions between % and f like so: printf("Your Net Pay is %.2f\n", net);. There are other formatting options that can be used with format specifiers and you can read more on them in the man pages by doing man printf since printf is not just a C function.

Resources