Code is not working (C) - c

I want to calculate the wages with struct and arrays but it is not working. You will understand the exercise better when you see the code. For some reason if in Wage and Days_Worked I enter a number(100 and 2)
Wagered[i].Gross_Wage = Wagered[i].Wage * Wagered[i].Days_Worked; Won't give me 200 but something else. Generally the programm won't work and I am trying to find the reason.
#include <stdio.h>
struct User
{
char First_Name[25];
char Last_Name[25];
int Wage, Days_Worked;
int Tax;
int Wage_Booking;
int Net_Wage;
int Gross_Wage;
};
int main()
{
int i;
int Wage_Summary = 0;
struct User Wagered[1];
for(i = 0; i < 1; i++)
{
/*printf("First Name: ");
scanf("%s", &Wagered[i].First_Name);
printf("\n");
printf("Last Name: ");
scanf("%s", &Wagered[i].Last_Name);
printf("\n");*/
printf("Wage: ");
scanf("%d", &Wagered[i].Wage);
printf("\n");
printf("Days He Worked: ");
scanf("%d", &Wagered[i].Days_Worked);
printf("\n");
Wagered[i].Gross_Wage = Wagered[i].Wage * Wagered[i].Days_Worked;
Wagered[i].Wage_Booking = Wagered[i].Gross_Wage * 0.2;
Wagered[i].Tax = (Wagered[i].Gross_Wage - Wagered[i].Wage_Booking) * 0.05;
Wagered[i].Net_Wage = Wagered[i].Gross_Wage - Wagered[i].Wage_Booking - Wagered[i].Tax;
Wage_Summary += Wagered[i].Net_Wage;
}
printf("The Summary of the Gross Wages is: %d\n", Wagered[i].Gross_Wage);
return 0;
}

This statement :
printf("The Summary of the Gross Wages is: %d\n", Wagered[i].Gross_Wage);
is outside your for loop. Therefore it will be executed when i has value 1, thus accessing Wagered[1].Gross_Wage, which does not exist Wagered[1] is out of your array's bounds. Move it inside your for loop, like this :
for(i = 0; i < 1; i++)
{
.
.
.
Wagered[i].Gross_Wage = Wagered[i].Wage * Wagered[i].Days_Worked;
Wagered[i].Wage_Booking = Wagered[i].Gross_Wage * 0.2;
Wagered[i].Tax = (Wagered[i].Gross_Wage - Wagered[i].Wage_Booking) * 0.05;
Wagered[i].Net_Wage = Wagered[i].Gross_Wage - Wagered[i].Wage_Booking - Wagered[i].Tax;
Wage_Summary += Wagered[i].Net_Wage;
printf("The Summary of the Gross Wages is: %d\n", Wagered[i].Gross_Wage);
}
and you will see the correct result printed.

Related

Retrieving A Value From A Void Function

I was recently given an assignment by one of my professors in which I have to write a piece of code in which it prompts for a salary, years of service, and then based on those two pieces of info it calculates a bonus. I've worked with functions declared as doubles, but this is my first time working with void functions. I'm having trouble understanding how I can get my first function to save the prompted values for years of service and salary and then use those in the next function to calculate the bonus. This is what I currently have:
#include <cstdio>
void GetInput()
{
double salary;
int years_service;
printf("Enter your salary: ");
scanf("%lf", &salary);
printf("How many years have your served for us? ");
scanf("%d", &years_service);
}
void CalcRaise()
{
//I initialized salary and years_service because they would not compile
//otherwise. As expected, it does run but since they are set to 0, the
//bonus will be zero.
double salary = 0;
int years_service = 0;
double bonusA;
double bonusB;
double bonusC;
bonusA = salary * .02;
bonusB = salary * .05;
bonusC = salary * .10;
if ( years_service < 2)
{
printf("Here is your bonus: %lf", bonusA);
}
else if ( years_service > 5 && years_service < 10)
{
printf("Here is your bonus: %lf", bonusB);
}
else
{
printf("Here is your bonus: %lf", bonusC);
}
return;
}
int main()
{
GetInput();
CalcRaise();
return 0;
}
As I mentioned, I'm just having trouble figuring out how to save the values from my first function and use those to calculate the bonus. Any help is appreciated. -Thanks
Make all the variables global, and initialize those variables in the starting stage itself.
#include <stdio.h>
#include <stdlib.h>
double salary = 0;
int years_service = 0;
double bonusA;
double bonusB;
double bonusC;
void GetInput()
{
printf("Enter your salary: ");
scanf("%lf", &salary);
printf("How many years have your served for us? ");
scanf("%d", &years_service);
}
void CalcRaise()
{
bonusA = salary * .02;
bonusB = salary * .05;
bonusC = salary * .10;
if (years_service < 2)
{
printf("Here is your bonus: %lf", bonusA);
}
else if (years_service > 5 && years_service < 10)
{
printf("Here is your bonus: %lf", bonusB);
}
else
{
printf("Here is your bonus: %lf", bonusC);
}
}
int main()
{
GetInput();
CalcRaise();
return 0;
}

Can't Print " * " in C

for some reason I am unable to print out "* " in my program. I want to print out * if the condition is met. the condition is if the rainfall that day is greater than the average.
under the mean column, i am getting weird symbols. i tried debugging to decimals and get -112 for ascii. i dont understand but i tried researching!
I am new to C so please be understanding. Just learned like 2 days ago!!.
Here is my code :
//Assignment one 9/20/2018
//Anthony Lomaistro and David Luong
//luongd5#student.lasalle.edu
//lomaistroa1#student.lasalle.edu
#include <stdio.h>
main() {
int n = 0; //counters for the loops
int x = 0; // counter for the loops
int counter = 0; // counter whenever i need to keep track of increments
int days_input = 0; // how many days we are keeping track of
int number_of_days = 0;
double rainfall_input = 0;
double rainfall_amount = 0; // how much rainfall per day
double rainfall_average = 0; // average of rainfall
double rainfall_total = 0;
double rainfall_counter = 0; // count how many days it rained above the average
int correct = 0;
double rainfall_array[50];//array that contains the user input
char rainfall_condition[50]; // array that contains the *
double sum = 0;
double average = 0;
double percent_days = 0; //rainfall % above average
double valid = 0;
double valid2 = 0;
printf("Welcome to Lomaistro and Luong's Rainfall Program \n");
printf("How many days would you like to keep track of? Please enter a value between 1 and 50: #%d:", n + 1);
//printf(number_of_days);
while (valid == 0) {
scanf_s("%d", &number_of_days);
if ((number_of_days > 50) || (number_of_days <= 0)) { // come back to this, this doesnt do anytihng
printf("Invalid value, please enter in a day that is between 1 and 50 \n");
}
else {
valid = 1;
}
}
//getting the user to enter in the rainfall
for (x = 0; x < number_of_days; x = x + 1) {
valid2 = 0;
while (valid2 == 0) {
printf("Enter rainfall (in inches): ");
scanf_s("%lf", &rainfall_amount);
if ((rainfall_amount >= 0) && (rainfall_amount <= 10)) {
valid2 = 1;
rainfall_array[x] = rainfall_amount;
}
else
printf("Please enter in a valid rainfall amount between 1 and 10");
}
}
//computing average
for (n = 0; n < number_of_days; n = n + 1) {
sum += rainfall_array[n];
average = sum / number_of_days;
}
printf("Mean daily rainfall(in inches): %lf", average);
//seeing if the * should be the array or not
for (n = 0; n < number_of_days; n = n + 1) {
if (rainfall_array[n] > average) {
rainfall_condition[n] = "*";
rainfall_counter = rainfall_counter + 1;
}
else
rainfall_condition[n] = "empty";
}
// print out the thing
printf("\n Days \t Amount \t >Mean \n");
printf("==============================\n");
for (n = 0; n < number_of_days; n = n + 1) {
printf("%d \t %f \t %c \n", n + 1, rainfall_array[n], rainfall_condition[n]);
}
percent_days = rainfall_counter / number_of_days;
percent_days = percent_days * 100;
printf("Number of days that rained above average : %f \n", rainfall_counter);
printf("Percentage of days that rained above average: %f%% \n", percent_days);
system("pause");
}
rainfall_condition is an array of char, but you're putting a pointer to a string literal in there when you use "*". Use '*' for a character literal instead. To be more specific, this line:
rainfall_condition[n] = "*";
Should be:
rainfall_condition[n] = '*';
Turn some warnings on in your compiler; the first line (what you have now) isn't valid C code and you should be seeing a diagnostic message to that effect.
Edit: now that I've read more of the code, it appears you want either a * or an empty in that column? In that case you want to change the variable declaration to:
char *rainfall_condition[50]; // array that contains the *
And then change the print statement to:
printf("%d \t %f \t %s \n", n + 1, rainfall_array[n], rainfall_condition[n]);

Printing the average of combined student marks using C

I've made this program below to calculate the average mark of a student.
Everything works well until I use -1, it is supposed to stop the program as is display the average of all students that have been entered, say Goodbye! and then terminate.
I think my calculations might be wrong though because it is printing the wrong result for the average marks of the students.
Thanks in Advance.
#include <stdio.h>
int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
for (i = 0; i < 2; i++)
{
printf("Enter assignment 1 mark (-1 to quit): ");
scanf("%d", &a_mark1);
if(a_mark1 == -1)
{
average_mark += final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
if ((average_mark > 1 ) && (average_mark < 100 ))
{
printf("The average student mark is %.2f%% \n", average_mark);
}
printf("Goodbye! \n");
return 0;
}
printf("Enter assignment 2 mark: ");
scanf("%d", &a_mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab_mark);
printf("Enter quiz mark: ");
scanf("%d", &quiz_mark);
printf("Enter exam mark: ");
scanf("%d", &exam_mark);
printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
}
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}
I think you need to rethink your logic a little bit. Why not use a while loop to control the flow. Then you can bail out of the program immediately if user inputs -1 right away. You should use an array to store the averages for each student, then you can loop through and find the class average as well.
-Your float final_mark function seems a little sketchy without any parenthesis.
-You should put your function prototype outside of main as well. See below changes.
#include <stdio.h>
#define MAX_STUDENTS 10 //define what the max number of students is
float final_mark(int mark1, int mark2, int lab, int quiz, int exam);
int main()
{
int i = 0, mark1 = 0, mark2 = 0,
lab = 0, quiz = 0, exam = 0;
int num_students;
float students_avg[MAX_STUDENTS] = {0}; //array to hold averages for students
float average = 0;
while (i < MAX_STUDENTS) {
printf("Enter assignment 1 mark (enter -1 to quit):\n");
scanf("%d", &mark1);
if (mark1 == -1)
break; //no more students, break out of while loop
printf("Enter assignment 2 mark: ");
scanf("%d", &mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab);
printf("Enter quiz mark: ");
scanf("%d", &quiz);
printf("Enter exam mark: ");
scanf("%d", &exam);
average = final_mark(mark1, mark2, lab, quiz, exam);
students_avg[i] = average; //add this average to array
printf("Student # %d average was %.2f\n", i, students_avg[i]);//debug info
i++;
}
num_students = i; //how many students grades did we read?
average = 0; //reset to 0 so we can use below
for (i = 0; i < num_students; i++)
average += students_avg[i];
if (num_students > 0)
printf("Class average is %.2f\n", average/num_students);
else
printf("Goodbye!\n");
return 0;
}
float final_mark(int mark1, int mark2, int lab, int quiz, int exam)
{
//we can just return the calculation
return ((mark1 * 0.1) + (mark2 * 0.15) + (lab * 0.15) + (quiz * 0.1) + (exam * 0.5));
}
Just erase two lines above printf("GOODBYE! \n"); you will get what you want.
maybe you have to initialized mark s variables to 0. and a_mark1 to 0 too if the user enter -1

Why does my code jump to else immediately?

#include <stdio.h>
int printMenu(int);
int studentglobal;
float getCarryMark(float);
float cm1;
main()
{
printf("-----------------------------------------------------\n");
printf("\t\tTotal Score calculator\n");
printf("-----------------------------------------------------\n");
int counter, x, studentcount = 1,sum = 0 ;
x = printMenu(studentglobal);
for (counter = 0; counter < x; counter++)
{
studentcount = studentcount + counter;
printf("Student : %d \n", studentcount);
getCarryMark(cm1);
if (cm1 >= 0 && cm1 <= 50)
{
printf("right range!!\n");
}
else
{
printf("INVALID RANGE!!!\n");
}
printf("%.2f\n", cm1);
}
}
int printMenu(int nstudent)
{
printf("Enter no of student: ");
scanf("%d", &nstudent);
return(nstudent);
}
float getCarryMark(float carrymark)
{
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}
So actually when I enter 200, it shows INVALID RANGE!!!, but when I enter 20 it still shows INVALID RANGE!!!. It somehow skipped the if statement. Please don't bother the other part, if I have any mistake tell me please. ert gf dfg dgd dg dfgd gd dg dg dgdfg
You need to return carrymark from getCarryMark:
float getCarryMark(float carrymark)
{
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}
You are missing a return statement in getCarryMarks method !
You missed the return statement in getCarryMark
getCarryMark function takes a parameter by value, modifies the value and returns it back, however, the returned value is never used. Modifying the parameter's value does not reflect this change to the outside since it has been passed by value.
I have partially updated the code so that it could execute the if statement. Please try the following code.
#include <stdio.h>
int printMenu(int);
int studentglobal;
float getCarryMark(float);
float cm1;
main()
{
printf("-----------------------------------------------------\n");
printf("\t\tTotal Score calculator\n");
printf("-----------------------------------------------------\n");
int counter, x, studentcount = 1,sum = 0 ;
x = printMenu(studentglobal);
for (counter = 0; counter < x; counter++)
{
studentcount = studentcount + counter;
printf("Student : %d \n", studentcount);
cm1 = getCarryMark();
if (cm1 >= 0 && cm1 <= 50)
{
printf("right range!!\n");
}
else
{
printf("INVALID RANGE!!!\n");
}
printf("%.2f\n", cm1);
}
}
int printMenu(int nstudent)
{
printf("Enter no of student: ");
scanf("%d", &nstudent);
return(nstudent);
}
float getCarryMark()
{
float carrymark = 0.0;
printf("Enter your carrymarks: ");
scanf("%f", &carrymark);
return(carrymark);
}

Compiler error when trying to print from struct

My assignment is to, using structs, get input of info on employees, and output their pay.
It appears to run properly until I get to the end and try to printf() the calculated results. The compiler tells me [Error] request for member '*' in something not a structure or union. (Replace * with ID, name, grossPay, netPay.)
Sorry if it's been asked; I'm still new to structs/pointers/etc, so I suspect it's a simple mistake. It's just not jumping out at me. I looked through some of the previous questions but many are situation-specific.
// Matt Posey - PP #20
#include <stdio.h>
struct employee
{
char ID[6];
char name[20];
float hours;
float payRate;
float grossPay;
float netPay;
};
int main()
{
int j, i = 0;
int employees;
printf("This program computes pay.\n");
printf("\nNumber of employees: ");
scanf("%d", &employees);
fseek(stdin,0,SEEK_END);
// Get data
for (i = 0; i < employees; i++)
{
j = i;
struct employee j;
printf("\nFor employee %d:", i+1);
printf("\nID: ");
gets(j.ID);
fseek(stdin,0,SEEK_END);
printf("Name: ");
gets(j.name);
fseek(stdin,0,SEEK_END);
printf("Pay rate: ");
scanf("%f", &j.payRate);
fseek(stdin,0,SEEK_END);
printf("Hours worked: ");
scanf("%f", &j.hours);
fseek(stdin,0,SEEK_END);
j.grossPay = j.hours * j.payRate;
if (j.hours > 40)
{
printf("Overtime!");
float OT = (j.hours - 40) * (j.payRate * 0.5);
j.grossPay += OT;
}
j.netPay = j.grossPay * 0.75;
}
// Output data
printf("\n\nID | Name | Gross Pay | Net Pay");
printf("\n------ | -------------------- | --------- | -------");
for (i = 0; i < employees; i++)
{
j = i;
printf("\n%c | %c | $%7.2f | $%7.2f", j.ID, j.name, j.grossPay, j.netPay);
}
return 0;
}
Several issues with the question code...
1)
// Get data
for (i = 0; i < employees; i++)
{
j = i;
struct employee j;
The variable j is only visible inside the scope (ie braces) where it is declared. Fix this by moving it to `main()''s scope:
int main()
{
int j, i = 0;
int employees;
struct employee j;
Of course, this causes another problem it that there is already an `int j' defined. Get rid of that:
int main()
{
int i = 0;
int employees;
struct employee j;
2) Next, you need j to be an array that can hold all the employees. Unfortunately, you don't know (at compile time) how many employees the user will require. So, just make a pointer to allocate some memory to later:
int main()
{
int i = 0;
int employees;
struct employee *j=NULL;
Let the user indicate how many employees, then allocate sufficient memory for the array:
printf("\nNumber of employees: ");
scanf("%d", &employees);
fseek(stdin,0,SEEK_END);
j = malloc(employees * sizeof(*j));
if(NULL == j)
{
fprintf(stdout, "malloc() failed.\n");
goto CLEANUP;
}
Then, put a 'goto label' just before the return statement:
CLEANUP:
return 0;
}
In order to use the malloc() function, you will have to include another header:
#include <stdio.h>
#include <stdlib.h> /* Added for 'malloc()' */
3) Now get rid of the j=i; thing:
// Get data
for (i = 0; i < employees; i++)
{
printf("\nFor employee %d:", i+1);
4) Now, everywhere j is referenced, reference it like an array:
printf("\nID: ");
gets(j[i].ID);
fseek(stdin,0,SEEK_END);
printf("Name: ");
gets(j[i].name);
fseek(stdin,0,SEEK_END);
printf("Pay rate: ");
scanf("%f", &j[i].payRate);
fseek(stdin,0,SEEK_END);
printf("Hours worked: ");
scanf("%f", &j[i].hours);
fseek(stdin,0,SEEK_END);
j[i].grossPay = j[i].hours * j[i].payRate;
if (j[i].hours > 40)
{
printf("Overtime!");
float OT = (j[i].hours - 40) * (j[i].payRate * 0.5);
j[i].grossPay += OT;
}
j[i].netPay = j[i].grossPay * 0.75;
And here too:
printf("\n%c | %c | $%7.2f | $%7.2f", j[i].ID, j[i].name, j[i].grossPay, j[i].netPay);
5) Get rid of the j = i; in main():
for (i = 0; i < employees; i++)
{
printf("\n%c | %c | $%7.2f | $%7.2f", j[i].ID, j[i].name, j[i].grossPay, j[i].netPay);
}
6) Fix the printf() format string. It should be printing strings, not characters:
printf("\n%s | %s | $%7.2f | $%7.2f", j[i].ID, j[i].name, j[i].grossPay, j[i].netPay);
Now the code is functional.
However, there is still some of the code that is risky. For example, fgets() should be used (instead of gets()) [as indicated by chris & McLovin], etc.
printf("\nID: ");
fgets(j[i].ID, sizeof(j[i].ID), stdin);
fseek(stdin,0,SEEK_END);
printf("Name: ");
fgets(j[i].name, sizeof(j[i].name), stdin);
And the report would be cleaner if there was an ending newline:
printf("\n");
CLEANUP:
return 0;
}
And as indicated by Ed Heal, this line is not needed:
fseek(stdin,0,SEEK_END);
SPOILER
You have used a name "name of a variable" twice.
First you say there's an int called j, then you stay there is a struct employee called j. Rename one or the other.
int j, i = 0;
(and much later)
j = i;
struct employee j;

Resources