Defining a variable "C programming" - c

This is my program below to calculate the mpg value, then convert it
to liter-per-100-km value.
My question is why when I define the mpg variable as you see in comment number 1 my program outputs wrong values but when I define it as you see on comment number 2, the program outputs correct values?
#include <stdio.h>
#define GAL_TO_LIT 3.785
#define MILE_TO_KM 1.609
int main()
{
float miles;
float gallons;
float mpg; //1 float mpg = miles / gallons;
printf("Enter the number of miles traveled: ");
scanf("%f", &miles);
printf("Enter the number of gallons gasoline consumed: ");
scanf("%f", &gallons);
mpg = miles / gallons; //2
printf("The miles-per-gallon value is: %.1f\n", mpg);
printf("The liters-per-100-km value is: %.1f\n",
100. / mpg * GAL_TO_LIT / MILE_TO_KM);
return 0;
}

When program execution reaches the line with the first comment, miles and gallons have indeterminate values since they have not been initializes nor assigned to. Accessing those values is undefined behaviour.
In the line with your 2nd comment miles and gallons have already got values by scanf() and everything is fine.

Actual values of miles and gallons have been assigned once you use scanf. Before that when the variable is initialized both variables are having some random "garbage" value.
I can see you have just started programming and my only advice will be to always perform the operations on variable once the proper value has been assigned to them (like in comment 2).

Related

"debug assertion failed! expression: result_pointer != nullptr" problem

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.

This C program gives zero average.Whats wrong in it?

#include <stdio.h>
#include <stdlib.h>
int main()
{
{
float test1Marks, test2Marks, test3Marks, averageMarks;
averageMarks = (test1Marks + test2Marks + test3Marks) / 3;
printf("Test 1 Marks:");
scanf("%f", &test1Marks);
printf("Test 2 Marks:");
scanf("%f", &test2Marks);
printf("Test 3 Marks:");
scanf("%f", &test3Marks);
printf("Average Marks of tests are:%f", averageMarks);
}
return 0;
}
Everything alright but the final output which gives average is wrong.
But when I assign values to two of the variables and input third ones value by scanf syntax then it gives the average otherwise not.
Move averageMarks=(test1Marks+test2Marks+test3Marks)/3; after the last scanf but before the print statement in which you are printing the average!
int main()
{
float test1Marks,test2Marks,test3Marks,averageMarks;
printf("Test 1 Marks:");
scanf("%f",&test1Marks);
printf("Test 2 Marks:");
scanf("%f",&test2Marks);
printf("Test 3 Marks:");
scanf("%f",&test3Marks);
/* Now with determined test1Marks, test2Marks, and test3Marks
values we can compute their average:
*/
averageMarks=(test1Marks+test2Marks+test3Marks)/3;
printf("Average Marks of tests are:%f",averageMarks);
return 0;
}
You need to read values into your variables before computing the average #John Bode 1
Compute averageMarks=(test1Marks+test2Marks+test3Marks)/3; after the values are read.
In another language this approach may work, yet C requires sequential evaluation.
averageMarks=(test1Marks+test2Marks+test3Marks)/3; is not a function, it is a series of statements to do something, where it adds the values in those variable at the time it is run, and then divides by 3, and assigns the result to averageMarks.
when you read in the values, scanf puts whatever value it reads into the variables when it is executed, and then you print out the averageMarks, which was already computed and stored earlier with the empty variables you made with the first statement.

How to prevent the wrong value entered by the user from getting stored in the variable?

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;
}

Making a C program return to the start and ask for input again if a user did not input the right value

it's my first post here so please be gentle to me. I've recently started a C programming class on my university and I got really interested in it. Since I'm working with audio (mixing / mastering music) I decided to try and make a simple program that would calculate the delay times in ms for the user defined BPM (Beats per minute).
What I am currently stuck with is the following: I want the program to return to the start and ask the user to input again if he typed in the wrong BPM (0 in this case).
I tried a do while loop however it didn't work quite right, my program would still calculate everything as if a user just typed in 0 and if I typed a correct value it would just loop endlessly.
If I do an if else statement it gives the user a message but I'd like to prompt the user for input again together with the message.
I know that this is a pretty simple and basic question but any help would be greatly appreciated.
Here is my code so far:
int main(){
float BPM;
printf("Please input the BPM: ");
scanf(" %f", &BPM);
do{
float HZ = 1000;
float HZ_Result;
float BPM_QuarterNote=(60/BPM)*1000;
float BPM_WholeNote=BPM_QuarterNote*4;
printf("\n\nDelay time for whole note is: %.2f ms or %.2f Hz", BPM_WholeNote, 1000/BPM_WholeNote);
float BPM_HalfNote=BPM_QuarterNote*2.0;
printf("\n\nDelay time for 1/2 note is: %.2f ms or %.2f Hz", BPM_HalfNote, 1000/BPM_HalfNote);
printf("\n\nDelay time for 1/4 note is: %.2f ms or %.2f Hz", BPM_QuarterNote, 1000/BPM_QuarterNote);
float BPM_EightNote=BPM_QuarterNote*0.5;
printf("\n\nDelay time for 1/8 note is: %.2f ms or %.2f Hz", BPM_EightNote, 1000/BPM_EightNote);
float BPM_SixteenthNote=BPM_QuarterNote*0.25;
printf("\n\nDelay time for 1/16 note is: %.2f ms or %.2f Hz", BPM_SixteenthNote, 1000/BPM_SixteenthNote);
float BPM_32ndNote=BPM_QuarterNote*0.125;
printf("\n\nDelay time for 1/32 note is: %.2f ms or %.2f Hz", BPM_32ndNote, 1000/BPM_32ndNote);
}while(BPM > 0);
return 0;
}
You can use a while loop instead of the if to test for your condition
eg
/* while loop execution */
while( BPM == 0 ) {
/* get my input values */
}
Add this code below you BPM declaration.
do{
printf("Please input the BPM: ");
scanf(" %f", &BPM);
}while(BPM==0.00);
A simple example of a user input loop that exits only when user is satisfied:
int main(void)
{
float fNum= 5.2;
double dpNum= 5.2;
long double ldFloat;
char quit[]={" "};
while(quit[0] != 'q')
{
printf("\n\nEnter a float number: ");
scanf("%f", &fNum);
printf("Enter a double precision number: ");
scanf("%Lf", &ldFloat);
... other stuff as needed
printf("Enter any key to continue or 'q' to exit.");
scanf("%s", quit);
}
return 0;
}
do {
printf("Please input the BPM: ");
} while (scanf("%f", &bpm) == 0 || bpm < 0);
This loop prints the question until the user inputted a valid floating point number and that said number is at least 0.

Monthly payments C program

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" ;)

Resources