// 6.1 Brain Teaser
#include <stdio.h>
int pills,weight;
float bottlenumber;
void load ()
{
printf("Enter the number of pills: ");
scanf("%d", &pills);
printf("Enter the weight of your pills: ");
scanf("%d", &weight);
}
void calc ()
{
bottlenumber = (weight - 210) / (float)0.1;
}
void print()
{
printf("The bottle number is %.f!", bottlenumber);
}
void main()
{
load();
calc();
print();
}
The user is suppose to enter 211.3. The answer then is suppose to be 13 but instead I get 10. I think it has to do with float aspect and the calculation part.
weight is an int, not a float, and you're reading it in a as an int, so if the user enters 211.3 then weight contains 211.
If you expect weight to be a float then you should declare it as such and read it in as such.
float weight;
...
printf("Enter the weight of your pills: ");
scanf("%f", &weight);
this line is the problem:
bottlenumber = (weight - 210) / (float)0.1;
remember, the value entered for weight is 3.
so 3 - 210 = -207
next divide -207 by 0.1 which = -2070
I suspect the line should be written somewhat differently
Related
I'm writing some code to calculate GPA and when I start a loop, one of my variables "numClasses" changes value to a huge number midway through the loop and I can't figure out what's going on.
#include <stdio.h>
int main()
{
float crdtHrs[] = {}; //Credit hours for this term
float numClasses; //Amount of classes taken this term
float qltyPoints[] = {}; //Quality points for term
float classes[] = {}; //Array for class grades
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
float a = numClasses; //using new variable because this way the loop works
for(int i = 1; i <= a; i++)
{
printf("\nGPA class #%d -> ", i);
scanf("%f", &classes[i - 1]);
printf("Credit hours for course -> ");
scanf("%f", &crdtHrs[i - 1]);
printf("%f", numClasses); //at some point of my loop numClasses changes value
}
return(0);
}
Nice zero length array buffer overrun. Boom. Let's arrange so the arrays are declared a little later so we can give them sizes.
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
int a = (int)numClasses;
float crdtHrs[a]; //Credit hours for this term
float qltyPoints[a]; //Quality points for term
float classes[a]; //Array for class grades
Now we allocate the arrays on the stack at the right size.
I am very new to C and am struggling with this code. I need to get the feet and inches of two athletes from user input using a structure, then total the inches of each athlete to determine the winner. The issue I'm having is that the value being returned doesn't make any sense. My guess is it has something to do with getting the address of the value instead of the actual value, but after changing some things around I just end up with errors or the program crashing. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
//Distance Structure
struct Distance
{
int feet;
float inches;
};
int main() {
//Initialize athelete structures
struct Distance athlete1;
struct Distance athlete2;
//Get values for athlete 1
printf("Enter the distance for athlete 1\n");
printf("Feet: ");
scanf("%d", &athlete1.feet);
printf("Inches: ");
scanf("%d", &athlete1.inches);
//Get values for athlete 2
printf("Enter the distance for athlete 2\n");
printf("Feet: ");
scanf("%d", &athlete2.feet);
printf("Inches: ");
scanf("%d", &athlete2.inches);
//Convert values to inches
float total1 = calculateInches(athlete1.feet, athlete1.inches);
float total2 = calculateInches(athlete2.feet, athlete2.inches);
//Print distance in inches
printf("\nAthlete 1 has a distance of %d inches\n", total1);
printf("Athlete 2 has a distance of %d inches\n\n", total2);
//Print the winner
if(total1 > total2){
printf("Athlete 1 wins!");
}
else if(total1 < total2){
printf("Athlete 2 wins!");
}
else{
printf("Tie!");
}
return 0;
}
//Calculate Inches
int calculateInches(feet, inches){
float total;
total = (feet*12) + inches;
return total;
}
There are few issues with your code:
The format specifier to be used whenever you are using float is %f instead you are using %d
Try forward declaring your calculateInches() method. Write it above the main() method or try using a function prototype. have a look at this link
Mention the right types for the arguments to the function float calculateInches(float feet, int inches). Related question
Working example: https://ideone.com/jsMZgv
I'm working on an assignment and trying to write the code to answer this question:
Write a program that computes the total weight of a cargo. The user has many types of boxes (numbered 1 to n). For each box type, the program asks the user about the weight and quantity. The program thencomputes and prints the total cargo weight.
In the output sample below, the user has three box types. For box type 2, the user enters the sentinel -1 to
indicate they’re done with the input. Your program should print Type 1, 2, 3, etc. as shown in the
output below.
Enter weight (lbs) of Type 1 box: 4
Enter quantity: 2
Enter weight (lbs) of Type 2 box: -1
The total weight is 8 lbs.
When i run this code it runs the first line to input weight but then gives me a segmentation fault and says (core dumped). -1 is the sentinel and even when the enter weight is inside the while loop the result is the same. What am I doing wrong? I'm sorry I'm new to C
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", weight);
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
This is not how you use scanf
scanf("%d", weight);
scanf("%d", quantity);
You should pass the address of the variable, not the value of the variable.
That would look like this:
scanf("%d", &weight);
scanf("%d", &quantity);
Your while loop depends on value weight. The value of weight never changes in your loop, so the loop can never exit.
This line:
total_weight= total_weight + (quantity*weight);
uses the value of total_weight, which was never initialized.
You should initialize your variables.
All in all, I think your fixed code should look like:
#include <stdio.h>
int main()
{
int weight = 0; //weight of boxes
int quantity = 0; //number of boxes
int total_weight = 0; //total weight
int n = 1;
while(weight!=-1)
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight); // Update weight **inside** the loop
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
Problem is in while condition, weight never change it's value so the condition always true so infinite loop.
Fix this statement scanf("%d", &weight);
Your problem is you are trying to assign a value to the pointer of quantity and weight, instead you need to put &quantity and &weight also you do not have another input for the weight, you should also use a do while instead of a while loop. It should look like this
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
do
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight);
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}while (weight != -1);
printf("The total weight is %0.2d", total_weight);
return 0;
}
After compiling, my GetInt function causes the printf statements within the function to be printed on the screen three times. I believe this was caused when I initialized all radius, base, and height to GetInt(void) but I see no other way of accurately initializing those variables. Please help!
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159
#include <stdio.h>
#include <math.h>
int GetInt(void);
double CalcTriangleArea(int base, int height);
double CalcCircleArea(int radius);
int main(void)
{
int radius, base, height;
double triangleArea;
double circleArea;
radius = GetInt();
base = GetInt();
height = GetInt();
triangleArea = CalcTriangleArea(base, height);
circleArea = CalcCircleArea(radius);
return(0);
}
int GetInt(void)
{
int x;
{
printf("Please enter a radius: \n\n");
scanf("%d", &x);
printf("Please enter a base: \n\n");
scanf("%d", &x);
printf("Please enter a height: \n\n");
scanf("%d", &x);
}
return(x);
}
double CalcTriangleArea(int base, int height)
{
double triangleArea;
printf("Triangle area is %.2f \n\n", triangleArea = .5*base*height);
return(0);
}
double CalcCircleArea(int radius)
{
double circleArea;
printf("Area is %.4f \n\n", radius, circleArea = PI * pow(radius, 2));
return(0);
}
A rule of thumb is to avoid repeating yourself whereever possible and don't repeat yourself. Imagine you want to change from two new lines (\n\n) to three (\n\n\n)? You would need to make that change three times.
Looking at the bare bones of GetInt, you are printing a prompt, two new lines, get a value and returning it. Thus, we can write the new function like this:
void getInt(char* prompt)
{
int x, numberOfConversions; // numConversions is the number of int's read from the keyboard buffer
printf("%s: \n\n", prompt);
numberOfConversions = scanf("%d", &x);
while (numberOfConversions != 1) // while the user did not enter a number
{
printf("Please enter a number: ");
numberOfConversions = scanf("%d", &x)"
}
return x; // Always returns a valid number
}
GetInt asks for, and reads, 3 distinct values, yet returns only the last one, every time it is called.
I think what you really want is to have GetInt ask for and return just 1 value, either passing it the prompt to print or printing it before calling it.
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)
)