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.
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...
I'm trying to prevent the user from entering a wrong value in this simple C program by using an if statement within while loop. But the problem is that whenever the user enters a wrong value, it gets stored in the variable and the same value is then use for further calculations.
Here's the actual program:
#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks\nEnter again: ");
scanf("%d", &marks);
}
total = total+marks;
a++;
}
average = total/(float)noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
The first problem is the inconsistency in your code. Inside the condition statement body, you wrote
scanf("%d", &marks);
which uses mismatched argument type for %d. This invokes undefined behavior. You should be using %f, as before.
That said,
you're relying on user to correct themselves in the second attempt, don't do that. Use a loop and only after you get a valid value, break out of that.
In the statement average = total/(float)noStudents;, you don't need the cast. One of the operand, total is already of float type, so the other operand will be automatically promoted and floating point division will take place, even in absence of the explicit cast.
Have slightly tweaked your code. Hope it helps. As already mentioned in one of the comment, don't expect user to give the correct value in out of range scenario. You should keep on asking the user to enter within the range unless he feeds in the correct value.
#include<stdio.h>
#include<stdlib.h>
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks.Enter again:\n ");
continue;
}
total = total+marks;
a++;
}
average = total/noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
#include <stdio.h>
int main () {
int days, flights, t, b;
float length, mean, sum;
printf("How many days has your dragon been practicing?\n");
scanf("%d", &days);
for(t=1; t<=days; t++) {
printf("How many flights were completed in day #%d?\n", t);
scanf("%d", &flights);
for(b=1; b<=flights; b++) {
printf("How long was flight #%d?\n", b);
scanf("%f", &length);
sum+=length;
}
mean = sum/flights;
printf("Day #%d: The average distance is %.3f.\n", t, mean);
}
}
the sum used to calculate the mean is supposed to be only the number from one iteration of the loop added together. instead the sum used numbers from the new iteration and old iteration added together.
If I understood your problem correctly, after the last printf() statement, you should reset sum to 0, like sum = 0;.
That said, the major issue in your code is that, you're using sum (an automatic storage local variable) while uninitialized. You should be initializing sum to some value (0, maybe) before making use (sum+=) of it. Otherwise, it it invokes undefined behavior.
To quote C11 standard, chapter ยง6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
sum won't clear because you don't clear it ! The point of writing code is to make your dumb machine(yeah dumb!) know when it's got to do what!
So immediately after
for(t=1;t<=days;t++)
{
Add this:
sum=0;
This will ensure that your sum value is reset every day your dragon takes a flight! Otherwise C will use some random garbage value as your sum and you would receive weird answers!
Some suggestions:
1) If you call scanf() just after you call printf(), there is no reason to use '\n' inside that printf at the end.
2) Always check scanf() for errors or your code is useless if errors occurs.
Now about your code:
When you use something like x+=y this means x = x + y.
So, in your case sum+=length means sum=sum+length. Do you know the value of sum? Yes is a garbage value.
About this line mean = sum/flights;, what is mean, sum and what is flights? Yes, first are float but second is int.
Now putting all together:
#include <stdio.h>
int main (void){
int days, flights, t, b;
float length, mean, sum=0;
printf("How many days has your dragon been practicing?: ");
if((scanf("%d", &days)) != 1){
printf("Error\n");
}
for(t=1; t<=days; t++) {
printf("How many flights were completed in day #%d?: ", t);
if((scanf("%d", &flights)) != 1){
printf("Error\n");
}
for(b=1; b<=flights; b++) {
printf("How long was flight #%d?\n", b);
if((scanf("%f", &length)) != 1){
printf("Error\n");
}
sum+=length;
}
mean = sum/(float)flights;
printf("Day #%d: The average distance is %.3f.\n", t, mean);
}
return 0;
}
Need some help with calculating the fixed monthly payment (P) required to fully amortize a loan of L dollars over a term of n months at a monthly interest rate of i. The given formula is: P = L[i(1 + i)n]/[(1 + i)n - 1]. I wrote a code but it didn't calculate Payment. I'm wondering if it is because I use double type together with int (for number of months) or the problem with formula?! Please help.
#include<stdio.h>
#include <math.h>
double calculatePayments(double rate, double loan, int payments);
int main() {
double principal, i, monthlyP;
int month;
printf ("Enter the principal amount: ");
scanf ("%f", &principal);
printf ("Enter the interest amount: ");
scanf ("%f", &i);
printf ("Enter the term in months: ");
scanf ("%d", &month);
monthlyP = calculatePayments (i, principal, month);
printf ("The monthly payment amount is %.2f: ", monthlyP);
return 0;
}
double calculatePayments(double rate, double loan, int payments) {
double mPayments;
mPayments = loan*(rate*(1 + rate)*payments)/((1 + rate)*payments - 1);
return mPayments;
}
Your scanf() requests %f format for a double; it should be %lf.
In addition to the need to fix the input (%lf instead of %f for doubles), I think your payment formula is wrong: since the future value of money grows exponentially, the formula should feature raising numbers to a certain power, which it does not.
The correct formula looks as follows (from here):
Since the loan needs to be paid off completely, FV is equal to zero.
Since pow(i+1, n) is used twice, it's a good idea to compute it once, and use the resultant variable in two places. The final version of this computation looks like this:
double calculatePayments(double rate, double loan, int payments) {
double mul = pow(1+rate, payments);
return (loan * mul * rate) / (mul - 1);
}
Demo on ideone computes the payment on $100,000 at 0.004% per month for 30 years at $524.67, which is the same value that excel's PMT function returns.
Note : When you enter the rate of 5.6% in your formula and in another calculator, don't forget that your formula takes the rate per month, not per year. Therefore, the rate that you plug into outside calculators must be 12 times what you enter into your calculator (for 5.6% annually you should enter 0.00466666
One of the first rules of debugging is to make sure you print the inputs to ensure that the program got the values you expected. It didn't, because you wrote:
scanf ("%f", &principal);
Since principal is a double, the format needs to be "%lf". Repeat for the interest rate. You should also check that the inputs succeeded:
if (scanf("%lf", &principal) != 1)
{
fprintf(stderr, "Failed to read principal\n");
return(1);
}
If you'd printed out the input values, you'd have known what was wrong immediately.
Read what dasblinkenlight said.
Also,
Fix your declarations and the variables you are using scanf() for.
principal should be loan. month should be payments.
i is okay. You need to calculate the monthly decimal number of the percentage given.
For instance,
interest = (i/100) /12;
Do that before your function call. Then just basically use dasblinkenlight's function at the bottom of your main.
hope you score a "10" ;)
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.