#include <stdio.h>
#include <math.h>
#define M_PI 3.14
int main(void)
{
// Declaring Variables
float time, p1, p2, p3, voltage, p3_num, p3_dem, epsilon;
int index, type;
// Asking user for time and index values into equation
printf("Please enter a time value: ");
scanf("%f", &time);
printf("Please enter an index value: ");
scanf("%d", &index);
// Calculate value for given time, part a, b, or c
printf("Do you want to run type a, b, or c?: ");
scanf("%d", &type);
char again = 'Y';
while (again == 'Y')
{
if (type == 'a') {
int going = 'Y';
while (going == 'Y')
{
// Different parts of formula to ensure accuracy
printf("Please enter an index value: ");
scanf("%d", &index);
p1 = ((3 / 2) - 12 / pow((M_PI), 2));
p2 = (1 / pow((double)(2 * index - 1), 2));
p3_num = ((2 * index - 1) * M_PI * time);
p3_dem = 3;
p3 = cos(p3_num / p3_dem);
voltage = p1 * p2 * p3;
printf("time = %f", time);
printf("index = %i", index);
printf("voltage = %f", voltage);
printf("Again? (Y/N)");
scanf("%c", &going);
}
}
}
}
There is more underneath, but this is the main bulk. What I am confused about is that none of this running, none. I start at the very beginning and comment out everything else, not even my print statement is running. What is wrong?
You should divide your program up into smaller function so you can test them individually.
For example here would be a function that reads in one integer.
int GetInteger(const char * msg)
{
//read up on c style formatting here is a source http://en.cppreference.com/w/c/io/fscanf
int i = 0;
printf("%s", msg);
scanf("%i", &i);
printf("Program confirms: %i\n", i);
return i;
}
This will help you down the road. Read up on SOLID principles and Test Driven Development.
Related
I'm very new to programming, and I'm doing a simple bot in C, that has a calculator function. I'm having some trouble in this piece of code:
char operation = get_char("Insert the mathematical operation: ");
float x = get_float("X: ");
float y = get_float("Y: ");
if (operation == 43)
{
float result = (x + y);
int rresult = round(result);
printf("X + Y = %i\n", rresult);
string confirmation = get_string("Need to do something more? ");
if (strcmp(confirmation, "Y") == 0)
{
return operation;
}
As you can see, this calculator ask the user for a char (*, /, + or - [its everything defined in the other parts of the code, I will not post it here just to be brief] that defines the math operation and then, after doing the calculation and printing the result, asks the user if he wants to do more calculations. If the answer is "Y" (yes), I want to restart this piece of code, asking for the char and the floats, and doing everything. I want to know the simplest way to do this, without making the code looks bad designed.
Also, I'm using CS50 IDE.
I don't have CS50, therefore, plain C. The construct you might want to use is a do-while loop.
#include <stdio.h>
#include <math.h>
char get_char(char * msg) {char c; printf("%s", msg); scanf(" %c", &c); return c;}
float get_float(char * msg) {float f; printf("%s", msg); scanf(" %f", &f); return f;}
int main() {
char confirmation = 'n';
do {
char operation = get_char("Insert the mathematical operation: ");
float x = get_float("X: ");
float y = get_float("Y: ");
if (operation == '+') {
float result = (x + y);
printf("Result in float: %f\n", result);
int rresult = round(result);
printf("X + Y = %i\n", rresult);
}
confirmation = get_char("Need to do something more [y/n]? ");
} while (confirmation == 'y');
return 0;
}
$ gcc -Wall dowhile.c
$ ./a.out
Insert the mathematical operation: +
X: 0.11
Y: 0.88
Result in float: 0.990000
X + Y = 1
Need to do something more [y/n]? y
Insert the mathematical operation: +
X: 0.1
Y: 0.1
Result in float: 0.200000
X + Y = 0
Need to do something more [y/n]? n
$
C code for calculating simple interest
#include <stdio.h>
int main()
{
float principle, rate, years;
float simpleInterest = (principle * rate * years)/100;
printf("Enter the principle");
scanf("%f", &principle);
printf("Enter the rate");
scanf("%f", &rate);
printf("Enter the years");
scanf("%f", &years);
printf("The simple interest is %f", simpleInterest);
}
C variables are not mathematical variables: they do not express a relationship:
int y = x + 1; // this does NOT mean that `y` is always equal to `x + 1`
Instead, statements are executed from top to down, and when a variable name comes up in the code, the C language will read its contents[1]. Therefore:
int x = 5;
// now x == 5
int y = x + 1;
// now x == 5 and y == 6
x = 8;
// now x == 8 and y == 6
That means that your code should be:
#include <stdio.h>
int main(void) // NOTE: use `int main(void)` instead of `int main()`
{
float principle, rate, years;
printf("Enter the principle");
scanf("%f", &principle);
printf("Enter the rate");
scanf("%f", &rate);
printf("Enter the years");
scanf("%f", &years);
float simpleInterest = (principle * rate * years) / 100.0f;
printf("The simple interest is %f\n", simpleInterest);
return 0;
}
NOTES:
[1] = not always true, because of short circuiting when using operators like && and ||, and because operators like sizeof do not evaluate the expressions. But this is beyond the scope of my answer.
I am in a intro to C programming course and I am a bit confused.
My input is not working correctly. When I run the program, the program will take the first input, then skip the rest of the prompts for inputs and generate a total.
What is going on? I am completely lost.
int main(void) {
/* declarations: */
double y, m1, s1, s2, m2, i;
char g; /* Do not remove this line */
/*Print the title of the program*/
printf(" MILEAGE SPEED INTERPOLATION\n");
printf("______________________________________________________________________\n");
printf("Enter in your first speed:\n"); //this is s1
scanf("%.1f", &s1);
printf("Enter in your mileage:\n"); //m will be mileage 1
scanf("%.1f", &m1); //mileage is y
printf("Enter in your second speed:\n"); //this is s2
scanf("%.1f", &s2);
printf("Enter in your second mileage:\n");
scanf("%.1f", &m2);
/*Get the needed input*/
/*get the interpolation from the user*/
printf("Enter your interpolation:\n"); //number between 1 and 2
scanf("%.lf", &i);
printf("______________________________________________________________________\n");
/*Statements that perform the desired task*/
// This equation is calculating from rpm to knots
y = m1 + (i - s1) * (m2 - m1) / (s2 - s1); //This will do the equation for us.
/* Printing of the results*/
// Trying to print the answer from above equation
printf("Your estimated value is %f: ", y);
/*Keeps the window open. Please do not alter this.*/
printf("\n\nEnter to q to quit.\n");
do {
g = getchar();
} while (g != 'q');
return 0;
}
You must use "%lf" for double with scanf()
if (scanf("%lf", &s1) != 1)
return -1; /* Bad input */
and you can't specify precision, instead you can specify a maximum number of characters.
I am confused on how to complete this for loop. The mission is to read input in unix. For the input if the radius is >0 it should prompt the user each time and then if <=0 it should terminate. I am going from centimeters to square inches. My current configuration requires 2 inputs (1 prompted, 1 not) before giving output to the console. Cheers.
#include <stdio.h>
#define PI 3.14159
main()
{
float r, a;
int y = 9999999;
for(int i =0; i <y; i++){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r>0){
r=r;
a = PI * r * r *2.54;
printf("Its area is %3.2f square inches.\n", a);
} else {}
}
}
Your code flow is the following:
for (infinite condition) {
scan input
if (input > 0) {
do things
}
else {
do nothing
}
}
So there's no way to exit out of the loop, that's why the break statement exists, to force quitting an iterative block of code:
while (true) {
scanf ("%f", &r);
if (r > 0) {
// do whatever;
}
else
break;
}
The break will stop the cycle when executed, just going out of the loop.
You may want to try using a while loop instead so that the question is continually prompted until the user inputs a value =>0. see if below helps (also your conversion factor was not quite right);
#include <stdio.h>
#define PI 3.14159
void main()
{
float r, a;
printf("Enter the cirle's radius (in centimeters):");
scanf("%f",&r);
while (r>0)
{
a=PI*r*r*0.155; // conversion from sqcm to sqin is ~0.155
printf("Its area is %3.2f square inches \n", a);
printf("Enter the cirle's radius (in centimeters):");
scanf("%f",&r);
}
}
r=1.0f;
// break if no. of cases exhausted or r is negative or zero
for(int i =0; i < y && r > 0; i++)
{
printf("Enter the circle's radius (in centimeters): ");
if( scanf ("%f", &r) == 1) // Always check for successful scanf
{
a = PI * r * r/2.54/2.54; //This is correct formula
printf("Its area is %3.2f square inches.\n", a);
}
}
Consider a while loop instead:
#include <stdio.h>
#define PI 3.14159
main(){
float r, a;
int continueBool = 1;
while(continueBool == 1){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r>0){
a = PI * r * r *2.54;
//the above formula may be wrong, so consider trying:
//a = PI * r * r/2.54/2.54;
printf("Its area is %3.2f square inches.\n", a);
}
else{
continueBool = 0;
}
}
}
The break statement can be dangerous if you are new to C programming, so I recommend not using it until you get a better understanding of C and break. If you do want to use break, then this could be your solution:
#include <stdio.h>
#define PI 3.14159
main(){
float r, a;
while(1){
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r<=0){
break;
}
a = PI * r * r *2.54;
//the above formula may be wrong, so consider trying:
//a = PI * r * r/2.54/2.54;
printf("Its area is %3.2f square inches.\n", a);
}
}
Use this:
for(int i =0; i < y; i++)
{
printf("Enter the circle's radius (in centimeters): ");
scanf ("%f", &r);
if(r > 0)
{
a = PI * r * r *2.54;
printf("Its area is %3.2f square inches.\n", a);
}
else
{
break;
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to write a function for my 1st semester c assignment. If anyone could help me I've written all of the assignment i just need to validate user input. This is what the teacher gave me... if this is not enough info i can post more
double get_double(void) function must be used to validate the input for each expense
and income. It will continuously prompt the user for a numeric value until it meets the
conditions. The value must be numeric and greater or equal to 0. If any character input
precedes or follows the number the input is to be treated as invalid.
#include <stdio.h>
#include <conio.h>
double get_expenses(double* pSchool, double* pLiving, double* pTransp, double* pOther); /* function prototype */
double get_income(double* pEmploy, double* pOther); /* function prototype */
double display_report(double School, double Living, double Transp, double OtherExp, double Employ, double OtherInc); /* function prototype */
char get_char(char* pRecalculate); /* function prototype */
void clear_buffer(void); /* function prototype */
double get_double(void); /* function prototype */
main() {
double school, living, transp, otherExp;
double employ, otherInc;
char recalculate;
int counter = 1;
while (counter > 0){
printf("Student Budget Planner\n");
printf("~~~~~~~~~~~~~~~~~~~\n");
printf("Input Set: %d\n\n", counter);
get_expenses(&school, &living, &transp, &otherExp);
get_income(&employ, &otherInc);
display_report(school, living, transp, otherExp, employ, otherInc);
clear_buffer();
get_char(&recalculate);
if (recalculate == 'Y' || recalculate == 'y'){
counter = counter + 1;
} else {
counter = 0;
}
}
return 0;
}
double get_expenses(double* pSchool, double* pLiving, double* pTransp, double* pOther) {
*pSchool = *pLiving = *pTransp = *pOther = 0;
double tuition, textbooks, supplies, rent, utilities, phone, groceries;
double entertainment, transportation, car, insurance, gas, other;
printf("School Expenses:\n");
printf("~~~~~~~~~~~~~~\n");
printf("Tuition (per semester): ");
scanf("%lf", &tuition);
printf("\nTextbooks(per semester): ");
scanf("%lf", &textbooks);
printf("\nSupplies: ");
scanf("%lf", &supplies);
*pSchool = (tuition / 4) + (textbooks / 4) + supplies;
printf("\n\nLiving Expenses:\n");
printf("~~~~~~~~~~~~~\n");
printf("Residence/Rent/Mortgage: ");
scanf("%lf", &rent);
printf("\nUtilities: ");
scanf("%lf", &utilities);
printf("\nPhone/Internet: ");
scanf("%lf", &phone);
printf("\nGroceries/Eating out: ");
scanf("%lf", &groceries);
printf("\nEntertainment: ");
scanf("%lf", &entertainment);
*pLiving = rent + utilities + phone + groceries + entertainment;
printf("\n\nTransportation: \n");
printf("~~~~~~~~~~~~~\n");
printf("Public Transportation: ");
scanf("%lf", &transportation);
printf("\nCar: ");
scanf("%lf", &car);
printf("\nAuto Insurance: ");
scanf("%lf", &insurance);
printf("\nGas/Maintenance: ");
scanf("%lf", &gas);
*pTransp = transportation + car + insurance + gas;
printf("\n\nOther: \n");
printf("~~~~~\n");
printf("Any other expenses: ");
scanf("%lf", &other);
*pOther = other;
return *pSchool, *pLiving, *pTransp, *pOther;
}
double get_income(double* pEmploy, double* pOther){
*pEmploy = *pOther = 0;
double wages, family, scholarship, other;
printf("\n\nEmployment income:\n");
printf("~~~~~~~~~~~~~~~~~\n");
printf("Expected Wages/Tips: ");
scanf("%lf", &wages);
*pEmploy = wages;
printf("\n\nOther income:\n");
printf("~~~~~~~~~~~\n");
printf("Family Support: ");
scanf("%lf", &family);
printf("\nScholarship/Bursaries (per semester): ");
scanf("%lf", &scholarship);
printf("\nOther: ");
scanf("%lf", &other);
*pOther = family + scholarship + other;
return *pEmploy, *pOther;
}
double display_report(double School, double Living, double Transp, double OtherExp, double Employ, double OtherInc) {
printf("\n\nStudent Name Budget Report\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("Expenses:\n");
printf("~~~~~~~~\n");
printf(" MONTHLY ANNUALY\n");
printf("School Expenses: $%.2lf $%.2lf\n", School, School * 12);
printf("Living Expenses: $%.2lf $%.2lf\n", Living, Living * 12);
printf("Transportation Expenses: $%.2lf $%.2lf\n", Transp, Transp * 12);
printf("Other Expenses: $%.2lf $%.2lf\n", OtherExp, OtherExp * 12);
printf("total Expenses: $%.2lf $%.2lf\n", School + Living + Transp + OtherExp, School * 12 + Living * 12 + Transp * 12 + OtherExp * 12);
printf("Income:\n");
printf("~~~~~~~\n");
printf("Employment Income: $%.2lf $%.2lf\n", Employ, Employ * 12);
printf("Other Income: $%.2lf $%.2lf\n", OtherInc, OtherInc * 12);
printf("Total Income: $%.2lf $%.2lf\n", Employ + OtherInc, Employ * 12 + OtherInc * 12);
printf("Total Savings Available for your Goals: $%.2lf $%.2lf\n", (Employ + OtherInc) - (School + Living + Transp + OtherExp), (Employ * 12 + OtherInc * 12)- (School * 12 + Living * 12 + Transp * 12 + OtherExp * 12));
return 0;
}
char get_char(char* pRecalculate){
int valid_input;
valid_input = 0;
while (valid_input == 0){
printf("\nWould you like to recalculate your budget? (Y/N): ");
scanf("%c", &*pRecalculate);
*pRecalculate = toupper(*pRecalculate);
if (*pRecalculate == 'Y' || *pRecalculate == 'y' || *pRecalculate == 'N' || *pRecalculate == 'n') valid_input = 1;
else printf("Error Invalid choice\n");
printf("\n");
}
return *pRecalculate;
}
void clear_buffer(void) {
while ( getchar() != '\n' );
}
double get_double()
{
// What to put here?
}
Think about the train of process, and think about the flowchart/decision tree you want your program or function to follow.
You don't want to stop asking the user for input until valid input has been entered. You are guaranteed to ask the user at least once, but might ask multiple times. The input is either valid or invalid.
Now we begin to draft some pseudo-code. Here's how I would do it:
double get_double(void)
{
double d;
int ask_again = 1; /* continue if 1 (true), exit if 0 (false) */
do {
/* display message to user to let them know to type a number */
/* read user input */
if (/* user input didn't input a valid double */)
{
/* display appropriate error message */
}
else if (/* user entered a double, but it wasn't greater than or equal to zero */)
{
/* display appropriate error message */
}
else /* user entered valid input, so ... */
{
/* ... do something to make sure the loop exists */
}
} while (/* we need to ask again */);
}
This yells do-while to me, so I wrote it in a do-while loop. I provided an int ask_again variable, but I leave it to you where it might be useful, if at all.
You should consider what real code should go where all the comments are.
Check with your course notes to see what techniques your teacher expects you to know to apply here.
Reading and sanitizing user-input is a notorious problem in all computer languages, especially C. StackOverflow can give you ideas of how you might perform a particular action.
Try this:
double get_double()
{
double d;
if (scanf("%lf", &d) != 1)
/* handle error */
reurn -1;
if (d < 0)
/* handle error */
return -1;
return d;
}
Or, as Keith Thompson pointed out, you can also be safe:
double get_double()
{
double d;
char *line = NULL;
size_t len;
getline(&line, &len, stdin);
if (line == NULL)
return -1;
d = strtod(line, NULL);
free(line);
if (d < 0)
/* handle error */
return -1;
return d;
}
You can use it like this (as there's no way to return all the entered doubles in one single double -- maybe you want an array, but the question specified the target signature as double (*)()):
double d;
while ((d = get_double()) >= 0)
{
/* do what you want */
}