pointers not pointing correctly and comparison warnings - c

the following short program asks user to enter # of hospital rooms (between 1-5), and asks for number of flowers, which cannot be a negative number.
Then, it picks based on how many rooms the price from the hospitalRoomsPrices_Array[5], and it also displays the total flowers multiplied by $2.50 each.
finally, total cost of room(s) price + flower costs is added
heres the code:
#include<stdio.h>
void getUserInput(int *numHospitalRooms, int *numFlowers);
int main()
{
float hospitalRoomsPrices_Array[5]={300.00,350.00,400.00,450.00,500.00};
int numHospitalRooms = 0;
int numFlowers = 0;
float flowerPricing = 2.50;
getUserInput(numHospitalRooms, numFlowers);
float flowerCost = numFlowers*flowerPricing;
float totalCost = (flowerCost + hospitalRoomsPrices_Array[numHospitalRooms]);
//
printf("\nCost for %d room(s): $%.2f", numHospitalRooms, hospitalRoomsPrices_Array[numHospitalRooms]);
printf("\nFlower(s) Cost: $%.2f \n", flowerCost);
printf("\nTotal cost: $%.2f", totalCost);
return 0;
}
void getUserInput(int *numHospitalRooms, int *numFlowers)
{
do {
printf("\nHow many hospital rooms: ");
scanf("%d", &numHospitalRooms);
if (numHospitalRooms < 1 || numHospitalRooms > 5)
{
printf("\nInvalid number of rooms, room number must be between 1-5!\n");
}
}while((numHospitalRooms < 1 || numHospitalRooms > 5));
do {
printf("\nEnter number of flowers: ");
scanf("%d", &numFlowers);
if (numFlowers < 0)
{
printf("\nInvalid number of flowers, negative values are not accepted!\n");
}
}while((numFlowers < 0));
}
i am getting a lot of warnings when i compile:
[Warning] passing argument 1 of 'getUserInput' makes pointer from
integer without a cast
[Note] expected 'int *' but argument is of type 'int'
[Warning] passing argument 2 of 'getUserInput' makes pointer from
integer without a cast
[Warning] comparison between pointer and integer
not only that, but entering a negative number isnt being taken into account at all in the getUserInput() conditional statements.
here is an example of the output:
How many hospital rooms: 6
Invalid number of rooms, room number must be between 1-5!
How many hospital rooms: -1
Invalid number of rooms, room number must be between 1-5!
How many hospital rooms: 5
Enter number of flowers: -1
Cost for 0 room(s): $300.00 Flower(s) Cost: $0.00
Total cost: $300.00
what am i missing? why are the warnings coming up like that and messing with the program?

after much thinking, i finally figured it out:
#include<stdio.h>
void getUserInput(int *numHospitalRooms, int *numFlowers);
int main()
{
float hospitalRoomsPrices_Array[5]={300.00,350.00,400.00,450.00,500.00};
int numHospitalRooms = 0;
int numFlowers = 0;
float flowerPricing = 2.50;
getUserInput(&numHospitalRooms, &numFlowers);
float flowerCost = numFlowers*flowerPricing;
float totalCost = (flowerCost + hospitalRoomsPrices_Array[numHospitalRooms - 1]);
printf("\nCost for %d room(s): $%.2f", numHospitalRooms, hospitalRoomsPrices_Array[numHospitalRooms - 1]);
printf("\nFlower(s) Cost: $%.2f \n", flowerCost);
printf("\nTotal cost: $%.2f", totalCost);
return 0;
}
void getUserInput(int *numHospitalRooms, int *numFlowers)
{
do {
printf("\nHow many hospital rooms: ");
scanf("%d", numHospitalRooms);
if (*numHospitalRooms < 1 || *numHospitalRooms > 5)
{
printf("\nInvalid number of rooms, room number must be between 1-5!\n");
}
}while((*numHospitalRooms < 1 || *numHospitalRooms > 5));
do {
printf("\nEnter number of flowers: ");
scanf("%d", numFlowers);
if (*numFlowers < 0)
{
printf("\nInvalid number of flowers, negative values are not accepted!\n");
}
}while((*numFlowers < 0));
}
this should be like this: getUserInput(&numHospitalRooms, &numFlowers);
and this should be like this:
scanf("%d", numHospitalRooms); //no appresand
There was no need for all that back and forth for such a simple mistake anyone could have pointed out from here. As a student trying to learn, this feels very discouraging to have to fight for learning my mistakes. a simple two lines of code recommendation like i posted now would have shined a bright day here instead of a negative atmosphere.

Related

Compound interest calculator giving incorrect answer

I have written a program to calculate compound interest.
Here is the code:
#include <stdio.h>
#include <math.h>
int main(void) {
float value, rate, years,r;
int column = 0, tmp;
printf("Enter money values: ");
scanf("%f",&value);
printf("Enter a interest rate: ");
scanf("%f",&rate);
printf("Enter number of years: ");
scanf("%f",&years);
printf("\nYears ");
tmp = rate + 4;
r = rate;
for (int a = rate; a <= tmp; a++) {
printf(" %d ", a);
column++;
}
for (int b = 1; b <= column; b++) {
printf("\n %d",b);
for (int i = 1; i<= column; i++) {
printf(" %.2f ", (float) pow ( (value)*(1.0+((r/100.0)/(1.0))) , (1.0*b))
r++;
}
r = rate;
printf("\n");
}
// I = P*R*T
// P= AMOUNT (value)
// R=RATE (r)
// T=YEARS (b)
return 0;
}
It asks the user for a value (money), interest rate, number of years and displays the interest rate like so:
Enter money values: 100
Enter a interest rate: 6
Enter number of years: 5
Years 6 7 8 9 10
1 106.00 107.00 108.00 109.00 110.00
2 11236.00 11449.00 11664.00 11881.00 12100.00
3 1191016.00 1225043.00 1259712.00 1295029.00 1331000.00
4 126247696.00 131079600.00 136048896.00 141158160.00 146410000.00
5 13382255616.00 14025517056.00 14693280768.00 15386240000.00 16105100288.00
But my problem is the floating point calculation.
As you may be able to tell the numbers in the output above and very long and have many trailing digits
which i am very confused about.
For example in the 2nd row the first output is 11236.00,
this is wrong since it should be outputting 112.36 but for some reason the decimal has moved
forward two spaces. Why is this? and how could i fix this problem and print the correct solution
with the decimal in the correct place.
You have the value inside the pow. So when you square for two years, you are squaring the amount. Move the (value)* to output the pow call.

Calculate the discount in a program in C language

I have a plan that gives the total price of the products and if the purchase is more than 200, it should give a 15% discount. But when displaying the final amount, it displays the zero:
#include <stdio.h>
#include <conio.h>
int main()
{
int count;
printf("plz enter number of product :");
scanf("%d", &count);
int price;
int allprice;
float discounted_price ;
int i = 0;
while(i<count)
{
printf("plz enter price %d : ",i+1);
scanf("%d", &price);
allprice +=price;
i++;
}
if(allprice>200)
{
float discount_amount = (15*allprice)/100;
float discounted_price = (allprice-discount_amount);
}
printf("price before discount : %d ",allprice);
printf("\n");
printf("price after discount : %d ",discounted_price);
return 0;
}
You have discounted_price twice.
Once where you calculate it inside the if.
Once outside, which you output.
Outputting hence ignores the calculated value.
Change
float discounted_price = (allprice-discount_amount);
to
discounted_price = (allprice-discount_amount);
And you also need to change the way of printing it, to match the float type
(and thereby avoid undefined behaviour).
printf("price after discount : %f ",discounted_price);
Finally, the amounts will be more precise if you avoid the integer division:
float discount_amount = (15*allprice)/100.0;
And for good measure, init the summation variable (though the effect of that is not always seen) :
int allprice =0;
For readining input by a human (i.e. prone to format errors) it would be wise to check the return value of scanf() and use other verification techniques. But that is beyond the scope of an answer to your question.
First, you should initialize allprice to zero in order to calculate the total.
The inital value of the variable, if not initialized is undefined.
The expression
(15*allprice)/100;
may result in zero because it's doing integer divion since all of the operands (15, allprice, 100) are integers. To avoid this, you can just convert one of the operands to a float, or just add a .0 after 100.
(15*allprice)/100.0f;
This should fix your problem. Let me know if it helps.
The resulting code should look like this:
#include <stdio.h>
#include<conio.h>
int main(){
int count;
printf("plz enter number of product :");
scanf("%d", &count);
int price;
int allprice = 0;
float discounted_price ;
int i = 0;
while(i<count)
{
printf("plz enter price %d : ",i+1);
scanf("%d", &price);
allprice +=price;
i++;
}
if(allprice>200)
{
float discount_amount = (15*allprice)/100.0f;
discounted_price = (allprice-discount_amount);
}
printf("price before discount : %d ",allprice);
printf("\n");
printf("price after discount : %f ",discounted_price);
return 0;
}

Issues finding average of elements

Working with Repl.it and trying to use a function in C to average the elements in a variable length array. My program works fine in every other i/o area other than the average which returns:
The average for that day is: -nan. Any insight on what the issue may be?
The goal is to receive user input as a double(for example, how many pints of blood were taken per hour over a 7 hr period and then use a function call to calculate the average amount for that seven hour period.
New code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double average(int size, float ary[*]);
int main(void)
{
char dayOne[8], dayTwo[8];
int size;
float ave;
printf("Over how many hours do you want to view donation amounts?: ");
scanf("%d", &size);
if (size < 7 || size > 7)
size = 7;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
{
float ary[size];
for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayOne, ave);
}
printf("\n\nEnter day that you want to see average donation amount for: ");
scanf("%s", dayTwo);
if(strcmp(dayOne, dayTwo)== 0)
printf("\nEnter a different day please: ");
scanf("%s", dayTwo);
{
float ary[size];
for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayTwo, ave);
}
return 0;
}
double average(int size, float ary[])
{
double sum = 0;
double ave;
for (int i = 0; i < size; i++)
sum += ary[i];
ave = (double)sum / size;
return ave;
}
This is wrong:
int ary[7];
…
scanf("%f", &ary[i]);
%f is for scanning a float, but ary[i] is an int. The resulting behavior is not defined.
This is wrong:
double size;
…
ave = average(size, ary);
Nothing in the “…” assigns a value to size, so it has no defined value when average is called.
Quite a few syntactical and logical changes to be made buddy. As Eric Postpischil has mentioned in his answer, your size variable isn't initialized to anything before use. And using %f for accepting integers is incorrect too. Along with these, there are a few other glitches which I will list below, with the corresponding fixes. I have also attached the full working code along with the output.
Error: size variable not initialized.
Fix:: Since you have a fixed number of hours, you can either use the 7 directly or through size. Hence initialize the variable while declaring it. And just a suggestion buddy, use int for size. ==> int size = 7;
Error: Accepting input for array values. The array ary is of type int, but you have used %f which is a format specifier for float.
Fix: Use %d which is the format specifier for int data type. ==> scanf("%d", &ary[i]);
Error: Format specifier used for printing the average value. You have used %f again which is for float while the variable ave for average if of type double.
Fix: Use %lf which is the format specifier for double. ==> printf("\nThe average for the 2nd day is: %.3lf", ave); The .3 before lf is just to limit the number of decimal points to 3. It is optional.
Error: You accept the second day and display a message if it is the same as the first day, but the scanf for this is out of the if loop. hence it prompts the user to input another name of the day regardless of whether the second input day is same as the first or not.
Fix: just move that scanf into the if loop where you check if that day is same as the previous one.
I wouldn't really call this one an error, because it's just an improvement which I find that needs to be done. You accept the second day which should be different from the first with the message that average would be found. But you are not calculating the average for this day. Hence I have included that part in the code.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double average(int, int [7]);
int main(void)
{
char dayOne[8], dayTwo[8];
int size = 7;
double ave;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
int ary[7];
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%d", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average for the 1st day is: %.3lf", ave);
printf("\n\nEnter day that you want to see average donation amount for:");
scanf("%s", dayTwo);
if(strcmp(dayOne, dayTwo)== 0) {
printf("\nEnter a different day please: ");
scanf("%s", dayTwo);
}
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%d", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average for the 2nd day is: %.3lf", ave);
return 0;
}
double average(int size, int ary[7])
{
int sum = 0;
double ave;
for (int i = 0; i < size; i++) {
sum = sum + ary[i];
}
ave = sum / size;
return ave;
}
OUTPUT:
Enter day that you want to see average donation amount for: Day1
Enter amount taken in hour 1: 1
Enter amount taken in hour 2: 2
Enter amount taken in hour 3: 3
Enter amount taken in hour 4: 4
Enter amount taken in hour 5: 5
Enter amount taken in hour 6: 6
Enter amount taken in hour 7: 7
The average for the 1st day is: 4.000
Enter day that you want to see average donation amount for: Day2
Enter amount taken in hour 1: 8
Enter amount taken in hour 2: 8
Enter amount taken in hour 3: 8
Enter amount taken in hour 4: 8
Enter amount taken in hour 5: 8
Enter amount taken in hour 6: 8
Enter amount taken in hour 7: 8
The average for the 2nd day is: 8.000
Hope this helps.
double size;
The size variable has not been set before calling the average function.
ave = average(size, ary);
May be size can be initialized to 0 and incremented in the for loop as given below
double size = 0;
double ave;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
{
int ary[7];
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
size++;
}
ave = average(size, ary);
printf("\nThe average for the day is: %f", ave);
}
If the goal is to receive user input as a double, the array used to hold those values should be double.
double ary[7];
instead of
int ary[7];

How to add total of multiple repeats in C?

I am writing a simple C program which takes data from user and does some maths. Here is my code:
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300 * 100;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100 * total_marks;
printf("Your final average for all semesters is %d", average);
}
The problem with this code is that when I run the program returns 0 for final average for all semesters.
I wanted to get the final average for all semesters. Lets say if user enters 3 for numbers of semester they want to check and then they will be enter marks 3 times and then final average will be displayed, but it only gives 0.
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300.0 * 100.0;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100.0 * total_marks;
printf("Your final average for all semesters is %d", average);
}
Rounding errors
It is probably because here:
total_marks = subtotal / 300 * 100;
subtotal is less than 300 * 100. And since both the operands of / are of type int, integer division is performed resulting in total_marks becoming 0.
Fix it by changing the type of total_marks to float, or more preferably, double. Then, cast one of the operands of / to float if you changed total_marks's type to float or double if you changed total_marks's type to double. The cast makes sure that integer division is not performed and floating-point division is performed.
You might need to do the same with average.
Fixed Code:
#include <stdio.h>
int main(void) {
int semester_1, grade_1, grade_2, grade_3, subtotal; /* Better to use an array */
double total_marks, average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = (double)subtotal / 300 * 100; /* Note the cast */
printf("Your average this semester is %f", total_marks); /* Note the change in the format specifier */
semester_1--;
}
average = (double)semester_1 / 100 * total_marks; /* Note the cast */
printf("Your final average for all semesters is %f", average); /* Note the change in the format specifier */
}
Your code has several issues. The first is the one pointed out by Cool Guy: dividing small integer by bigger integer will lead to the result being zero due to integer truncation.
The second is that you aren't keeping a running total, and you're decrementing the number of semesters for your loop counter.
You should add a new variable that stores the cumulative sum of each semester, and you should save the initial value of semester_1
(Also, style-wise,
for (int i = 0; i < num_semesters; i++)
is much more readable than (and preserves the value of num_semesters)
while(semester_1 > 0)
)

Cash Register Program - C

Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}

Resources