um hello, well I tried to compile my code and it works fine, then run it, at first its working, until I input a character it suddenly crash. Do you know whats wrong with it? BTW Im just a beginner in programming so any suggestions or criticize is welcome. Thanks!
#include <stdio.h>
int main ()
{
char w;
int a, b;
float cola, change, rb, pep;
printf("Welcome! Please choose your drink from these beverages! Press the following buttons to order; \nA - Cola \nB - Root Beer \nC - Pepsi \n");
scanf("%c", w );
if(w=='A'){
printf("\nYou chose Cola!\n This cost $0.75.\n How many would you like to buy?");
scanf("%d", &a);
cola=a*.75;
printf("\nYou bought %d cola/colas. That will be %f. How much is your money?/n", a,cola);
scanf("%d", b);
change=b-cola;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else if(w=='B'){
printf("\nYou chose Root Beer!\n This cost $1.00.\n How many would you like to buy?");
scanf("%d", &a);
rb=a*1.00;
printf("\nYou bought %d root beer/beers. That will be %f. How much is your money?/n", a,rb);
scanf("%d", b);
change=b-rb;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else if(w == 'C'){
printf("\nYou chose Pepsi!\n This cost $1.50.\n How many would you like to buy?");
scanf("%d", &a);
pep=a*1.50;
printf("\nYou bought %d pepsi/s. That will be %f. How much is your money?/n", a,pep);
scanf("%d", b);
change=b-pep;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else{printf("Please come again./n");}
return 0;
}
These lines:
scanf("%d", b);
scanf("%c", w );
will crash. You need to pass a pointers to b and w instead:
scanf("%d", &b);
scanf("%c", &w );
The scanf function takes an address in memory as argument, in other words your input value needs a place in memory to store and for that you need to give an address,
http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm here will explain more about it.
Suggestion:If you will continue programming in your life, you should start naming the variables better, for example in your case : a should be numberOfDrinks and b should be moneyAmount or something similar, you will see when you will be working on a bigger project how important this is
Suggestion/Tip:You should start learning how to work in a modular way, meaning you should use functions , because it's best practice and you can reuse the code as many times as you like in the program, and it's easier to test also.
Related
Good day, I am practicing about Arithmetic and started to experiment a bit and got confused. How can I total the liter, refueled, and tendered?
#include <stdio.h>
int main()
{
int liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f",&liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f",&refueled);
printf("Enter the amount tendered: ");
scanf("%f",&tendered);
printf("your change is %.2f pesos. Thank you and come again!", changed = liter * refueled - tendered);
return 0;
}
It seems like float is more appropriate for all your variables (liter, refueled, tendered, changed). There's no reason to allow only integer amounts of fuel etc. You also scanfed them using "%f" which is used for floats.
It's better to assign changed in a separate line, or alternatively get rid of it altogether and simply put the mathematical expression in the printf call.
You inverted the value of changed. Should be tendered - liter * refueled.
Better version:
#include <stdio.h>
int error_handler(/*error params*/)
{
int errCode{ 1 };
// Error handling based on the params, set errCode ...
return errCode;
}
float get_change(float liter, float refueled, float tendered)
{
return tendered - liter * refueled;
}
int main()
{
float liter{ 0 }, refueled{ 0 }, tendered{ 0 };
printf("Enter the price of the fuel per liter: ");
if (scanf("%f", &liter) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the number of liters the customer wants refueled: ");
if (scanf("%f", &refueled) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the amount tendered: ");
if (scanf("%f", &tendered) != 1) {
return error_handler(/*error params*/);
}
printf("your change is %.2f pesos. Thank you and come again!\n", get_change(liter, refueled, tendered));
return 0;
}
Update:
Following the comments below I updated my solution with:
Skeleton for error handling for scanf.
A separate function for the change calculation. In this case it seems a bit contrived, but it's correct from a methodical software engineering point of view (imagine this calculation getting a lot more complex in some real life scenario). Note: you can further apply this principle and extract for example the code for getting input from the user to a separate function. In my code above I decided it is enough to demonstrate it with get_change and error_handler.
Your scanning attempts, e.g. scanf("%f",&liter); uses the format specifier for float, but gives the address of an integer.
That causes undefined behaviour, which means "do not do this" for practicals (otherwise look up the term, or for fun "nasal demons").
The simplest fix (assuming you input integer values) is to switch to "%d".
If you instead switch to using float for the variable (probably necessary), you should know, for the cases of currency (e.g. tendered), that a very recommended best practice is to then convert to an integer variable which counts the smallest denomination, e.g. cents.
I took the answer of wohlstad, which was nearly perfect and added a function for your calculation...
#include <stdio.h>
fload calculation(fload tendered, fload liter, fload refueled);
int main()
{
float liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f", &liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f", &refueled);
printf("Enter the amount tendered: ");
scanf("%f", &tendered);
changed = calculation(tendered, liter, refueled);
printf("your change is %.2f pesos. Thank you and come again!", changed);
return 0;
}
fload calculation(fload tendered, fload liter, fload refueled){
fload calcVal = tendered - liter * refueled;
return calcVal;
}
Now you can edit your calculation like you need it, adding more or less things etc...
There's some problem with the 'calculate the total' part but I'm unsure what it is. Everything else runs fine besides it.. I get the "result_pointer != nullptr" error everytime.
void CalculateTotal(double pricePerGallon, double* totalPtr)
//input price per gallon
//declare, ask and get the number of gallons
//calculate the total
//input/output parameter for the total
{
//declare, ask and get the number of gallons
int numGal = 0;
double tot;
printf("Enter the number of gallons requested: ");
scanf("%d", numGal);
//calculate the total
tot = numGal * pricePerGallon;
*totalPtr = tot;
printf("Your total is %f.", totalPtr);
}
unsure if it matters, but I called it in another function definition like so:
CalculateTotal(itemNumber, &total);
(I'm just learning programming for my class, so the simpler the explanation, the better. This is not C++ btw, just C.)
scanf should get a pointer, so your call to the function is wrong and should be as follows:
scanf("%d", &numGal);
You also have a bug in your call to printf, which should be as follows:
printf("Your total is %f.", *totalPtr);
You need to use the indirection operator due to the fact that totalPtr is a pointer.
I am taking my first programming class this semester and I can't figure out what is going on with my program. I have to write a program that calculates the total amount of money after so many years with interest. The formula is y=p*(1+r)^n
Anyways, whenever I run my code it comes up as "_ has stopped working" and closes.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main (void)
{
double p, r, n, y;
printf("Enter the interest rate>");
scanf("%lf", r);
printf("Enter the principle amount of money invested>");
scanf("%lf", p);
printf("Enter the number of years invested>");
scanf("%lf", n);
y = pow(p*(1+r),n);
printf("The total amount of money is %f.\n", y);
system("PAUSE");
return (0);
}
I have tried googling it and it seems like it might have something to do with "initializing", but I'm not sure what that means or how to do it. Any help is greatly appreciated!
First of all the scanf() function expects the adress of a variable not the variable itself, so it should be used like that scanf("%lf", &r);Try it and you will be okay
And secondly never use system("PAUSE")!!
It is platform specific (windows) and it is wrong system("pause"); - Why is it wrong?
You are learning to program in a wrong way by using system(PAUSE) and in the above link you can see why!
This code was written and tested on linux platform.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main (void)
{
double p, r, n, y, value;
int a = 3, b = 2;
printf("Enter the interest rate>");
scanf("%lf", &r);
printf("Enter the principle amount of money invested>");
scanf("%lf", &p);
printf("Enter the number of years invested>");
scanf("%lf", &n);
value = p * (r + 1);
y = pow(value, n);
printf("The total amount of money is %f.\n", y);
//system("PAUSE");
return (0);
}
to compile this code in linux use,
gcc code.c -lm
I dont know why, I am forced to include -lm at compile time even though I am adding #include. Any one feel free to update the answer on this.
Update.
Please see this answer for why we must use -lm Undefined reference to 'pow' even though -lm is a compile flag. [C]
I'm trying to practice making if-statements and am having very little luck with this. Right now I'm trying to make a trigonometric calculator, a very simple one, using if statements, but I can't get it working. The actual problem occurs after input the trig function (sine, cosine, tangent). This is what happens.
1. I compile it
2. It outputs the user prompt
3. I input the function and hit enter
4. The program jumps to a new blank line
5. Nothing happens and the program closes if I press enter
Here is the code itself. Please be kind if I've done something monumentally stupid, I'm pretty new to C.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if (x == sine)
{ printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
sine = o / h;
printf("The sine is equal to %f", sine);
}
if (x == cosine)
{ printf("Enter the value of the adjacent leg: ");
scanf("%f", &a);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
cosine = a / h;
printf("The cosine is equal to %f", cosine);
}
if (x == tangent)
{ printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the adjacent leg: ");
scanf("%f", &a);
tangent = o / a;
printf("The tangent is equal to %f", tangent);
}
getch();
}
Thank you to everyone who who was actually helpful and wasn't rude about my lack of understanding, I didn't realize I had to add a numerical character instead of just a character.
Simple (minimal) fixes
Yes, you're on the verge of doing various things that an experienced programmer would call silly, but they're the sorts of mistakes that novices make (you're neither the first nor the last to make them).
int main(void)
{
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if (x == sine)
The primary problem is that you've not given sine, cosine or tangent values, so you've no idea what to enter to make the equality work.
The secondary problem is that comparing floating point numbers for equality is not a good idea.
You'd probably do best with something like:
int main(void)
{
int x;
float a, o, h;
enum { sine, cosine, tangent };
printf("Enter the trig function (0 = sine, 1 = cosine, 2 = tangent): ");
scanf("%d", &x);
if (x == sine)
This is more or less orthodox, and reading and comparing integers for equality is reliable. You would have to change the actions since I've pre-empted the names sine, cosine, and tangent as enumeration (integer) constants. You could work around that by using upper-case names for the constants (that's pretty orthodox), or using a prefix for the names, or ...
int main(void)
{
int x;
float a, o, h;
float sine, cosine, tangent;
enum { SINE, COSINE, TANGENT };
printf("Enter the trig function (0 = sine, 1 = cosine, 2 = tangent): ");
scanf("%d", &x);
if (x == SINE)
Friendlier input
As you might gather from the comments below, it would be better to allow the user to enter the name of the function they'd like to enter instead of making them enter a coded number. That's a little trickier to code up reliably, which is the main reason why I left the answer above using numbers.
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[4096];
printf("Enter trig function you wish to calculate: ");
if (fgets(line, sizeof(line), stdin) != 0)
{
char *nl = strchr(line, '\n');
if (nl != 0)
*nl = '\0';
if (strcmp(line, "sine") == 0)
{
/* Process sine */
}
else if (strcmp(line, "cosine") == 0)
{
/* Process cosine */
}
else if (strcmp(line, "tangent") == 0)
{
/* Process tangent */
}
else
{
fprintf(stderr, "Unrecognized trig function (%s)\n", line);
}
}
}
The 4096 is simply a big round number that's so long that it is very unlikely that anyone will ever enter a line that is longer than that. If they do enter such a line, then GIGO and they get what they deserve (which will be a polite error message that the name they entered was not recognized).
This is still not wonderful code. It might be reasonable to strip leading and trailing white space, and maybe case-convert the input to lower case, and one of the messages should probably identify the valid function names. It would be possible to have the code loop repeatedly, but then you'd need a function to prompt and read the response, etc. All of which adds usability at the expense of more code which complicates things unnecessarily for a beginning programmer.
Your if statements aren't working because you're comparing the input value, x, with a floating point value that hasn't been set. I think what you want to do is this:
int x;
printf("Enter the trig function you wish to calculate\n");
printf("1=sine, 2=cosine, 3=tangent: ");
scanf("%d", &x);
if (x == 1)
{
// do sine
}
else if (x == 2)
{
// do cosine
}
else if (x == 3)
{
// do tangent
}
else
{
printf("I don't know that function.\n");
}
Monumentally stupid? Naw. It's an easy kind of mistake to make when you first start programming. Stick with it. We've all been there.
I'm not sure what you are entering into the program to begin with, but this is where your error is. If you are entering a character array (a "string"), and that is being passed to x, you can't compare that with a floating point value. Also, your sine, cosine, and tangent variables have no value/have not been assigned anything. To solve your issue, assign your variables a number, such as float sine = 1; and make sure what you enter into the command line to pass to x is a number. If you want to enter "cosine", and pass that value to x, then you will have to change your x variable to a char array, such as char[] x = "", and then change your sine, cosine, and tangent variables to be character arrays as well. If you do change your variables to arrays, remember to remove the & from the scanf statement, like this -> scanf("%s", x);.
Right now, this code:
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if(x == sine)
...reads a value into x, but then compares it to the current value of sine. Unfortunately, you haven't initialized sine, so it's comparing to some unknown, semi-random value.
When you compare to cosine and tangent, you're doing more of the same.
None of these comparisons has a meaningful result (e.g., they might easily all be true).
At a guess, you probably want to have the user enter a string, and compare that to the values "sine", "cosine", and "tangent", using strcmp.
This is a question that I have found on this site but the responses were not directly related to what I believe my problem is. I am a little embarrassed because I'm still very much an amateur. I am asking the user for how many GPAs they would like to enter. Then I am asking for input for each index. The problem is each index is returning 0. So I'm pretty sure I am messing up either the variable type or possibly the way I am incrementing the index. This is a homework problem and I am looking more for guidance than a complete give away.
#include<stdio.h>
main()
{
char Rspns;
int i, toCount, Total;
float GPA[toCount];
printf("\n\tYou can average up to 30 GPAs.");
printf("\n\tPlease choose how many GPAs you would like to average:");
scanf(" %d" , &toCount);
//assign how many indexes array should have
for(i = 0; i<toCount; i++)
GPA[i] = i++;
do
{
system("cls");
printf("\n\nEnter a GPA:");
scanf(" %f" , &GPA);
printf(" %f" , GPA[i]);
Total += GPA[i];
getch();
system("cls");
printf("\n\n\tWould you like to average the current amount of GPA's?");
printf("\n\nY/N: ");
scanf(" %c" , &Rspns);
if(Rspns == 'y' || Rspns == 'Y')
{
Total = Total / toCount;
printf("The average of those GPAs is %.1f" , Total);
getch();
}// end response
}while(i<=toCount);//end forCount
Total = Total / toCount;
}
int i, toCount, Total;
float GPA[toCount];
toCount is not initialized at this point.
Total += GPA[i];
same here, Total starts with an indeterminate value.
This
scanf(" %f" , &GPA);
is absolutely not what you want to do: remember, arrays and pointers are closely related in C - see this SO answer.
scanf(" %f" , &(GPA[i]) );
will scan the value into the i'th element of the array
I think you should be scanning into the specific float as opposed to scanning into the whole array
scanf("%f", &GPA[i]);
also, check your types for printf, the compiler is spewing out warnings.
Either initialise your GPA array to be a fixed size and validate toCount to be between 1 and the maximum, or use the memory allocation functions malloc or calloc to dynamically allocate your GPA array once you know the size (and free when finished with it).
I can't work out what you are trying to do where you say "assign how many indexes array should have", but there's no need to enter values into the array that you are going to subsequently overwrite (you can use calloc as described above to initialise them all to zero). Note that you should scan into the ith element of the GPA array (&GPA[i]), not into &GPA which is always the first element.
Also, be careful about the i++ because you are incremementing i twice each loop. Although that part of your code is unnecessary, it's a trap to watch out for in general.