#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.
Related
I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}
I am very new to C and to programming and I am having issues with getting the average of 5 numbers. I have tried everything I could think of and I have not clue why I am not getting a number besides 0. My code is:
#include <stdio.h>
int main (void)
{
long int first,second,third,fourth,fifth, sum;
float avg = (first+second+third+fourth+fifth)/5;
printf("Please put in five numbers\n");
scanf("%d%d%d%d%d", &first, &second, &third, &fourth, &fifth);
printf("You entered: %d %d %d %d %d\n" , first, second, third, fourth, fifth);
sum = first+second+third+fourth+fifth;
printf("The sum of the numbers you entered is %d\n",
sum);
printf("The average is %d\n", avg);
return 0;
}
I think the problem is that you are initialising average value with the variables that are given after calculating average .Try to calculate average value after giving the variables i.e first,second,third,fourth and fifth.
The main problem is that you calculate the average before getting the numbers. The values of the uninitialized variables happened to be 0, and the average of five zeros is a zero, too.
The second problem is that you divide a sum of integer numbers by another integer number. Integer division discards the fractional part of the quotient.
The line:
float avg = (first+second+third+fourth+fifth)/5;
must be moved after scanf, and 5 must become 5.0. The result should be displayed as a floating-point number with %f, not with %d.
There are four problems in your code :
You are calculating average before you take in variable.
You are dividing a sum of integer with other integer due to which , the fractional part will truncate.Integer division truncates the fractional part.
You are printing avg which you defined as float with format specifier %d so it will cause undefined behaviour.
You are using %d specifier for long int , it should %ld.
Taking Into Account All These Problem Your Code Becomes.
#include <stdio.h>
int main (void){
long int first,second,third,fourth,fifth, sum;
printf("Please put in five numbers\n");
scanf("%ld%ld%ld%ld%ld", &first, &second, &third, &fourth, &fifth);
//Changed Due To Problem 4.
printf("You entered: %ld %ld %ld %ld %ld\n" , first, second, third, fourth, fifth);
sum = first+second+third+fourth+fifth;
float avg = (sum)/5.0; //Changed Problem No.2 and N0.1
printf("The sum of the numbers you entered is %ld\n", //Changed Due To Problem 4.
sum);
printf("The average is %f\n", avg); //Changed Problem No.3
return 0;
}
Tip
Always Try To solve the problem yourself before asking for help , it will benefit you more.
And First Have It Ready On a Paper Before Coding , it will decrease many bugs.
I'm trying to get the max and min numbers from a contiunous scanf, but I can't seem to work it out. I get time limit exceeded. I need to do it as simple as it gets for a hw as I'm starting to learn C. Any suggestions?
#include <stdio.h>
int main(void) {
int a,b,z,f;
b=1;
while(a > -1){
scanf("%i", &a);
//printf("%i", a);
if((b>a)){
z=a;
}
if((b<a)){
f=a;
}
b=a;
}
printf("Maximum number is: %i\n", f);
printf("Minimum number is: %i", z);
}
You never initialize a before the while loop starts. Set it to 0 when you declare it.
Also, the minimum number will always be the last number you enter to break out of the loop. You probably want to do a check for that right after the scanf.
You're also not doing a proper check against the current min and max. You should be checking a against z and f, not b, and f and z need to be initialized to proper starting values. And while you're at it, change z to min and f to max so they're more descriptive.
If the end of the input is reached, a is not converted and undefined, but itwill very likely retain its old value and the condition may never become false. scanf returns a value: The number of items converted or the special value EOF if the end of input has been reached. Use it.
When you first use a, it is uninitialised and may well be negative. Your algorithm is also not correct. It doesn't find the min and max numbers, it tests how many numbers are greater than the previous number and how many are smaller with a strange result for the first number.
I'll let you work out the min/max logic by yourself, but here's a skeleton for numerical input, which stops at the end of input or at any non-numeric or negative input:
#include <stdio.h>
int main(void)
{
int a;
while (scanf("%i", &a) == 1 && a > -1) {
// process a
}
printf("Max: %i\n", amax);
printf("Min: %i\n", amin);
return 0;
}
I'm in a programming class right now, and was asked to create a program that calculated the sum of a user's input for multiple numbers--then calculate the nth root of the sum. If the number they input was less than 0, the loop is supposed to discard the less than 0 number, then ask again.
Unfortunately, no matter what number I input--it displays "Value needs to be greater than zero!" I tried putting a fflush(stdin); statement in the loop, but that didn't seem to do anything.
Here is my code. I really appreciate any and all help.
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
int mTotalNums, mNth; //amount of numbers in set
float mProd = 1, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
mNth = mTotalNums; //set the value of mTotalNums equal to mNth becuase we'll lose the original value of mTotalNums after the loop
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
}
mNroot = pow(mProd, (1 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
"%lf" is the scanf format for a double, but x is declared as float.
To scan a float, you have to use the %f format.
Note also that mTotalNums is not decremented in the loop, so that it will never
terminate.
Read the documentation of scanf(3). Since x is declared as a float, use %f as the scanf format control string. Also, take into account the result of scanf (it would be 1 if successfully read one item).
You should enable all warnings and debug info in your compiler, then learn how to use the debugger (notably to run your program step by step, display local variables, etc....).
(On Linux, if compiling with gcc -Wall -g you would get a useful warning, and the gdb debugger would be helpful...)
Try these modifications to your program (added comments with changes made)
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
//amount of numbers in set
int mTotalNums, mNth;
// Change to double for added precision
double mProd = 1.0, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
// Set the value of mTotalNums equal to mNth becuase
// we'll lose the original value of mTotalNums after the loop
mNth = mTotalNums;
// Don't forget to decrement the loop counter
while (mTotalNums-- > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else {
printf("\nValue needs to be greater than zero!\n");
}
}
// Change to 1.0 to force compiler to treat as a double
mNroot = pow(mProd, (1.0 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
You mention "calculate the nth root of the sum", but your loop is clearly tallying the cumulative product. To change it to calculate the sum, try the following additions:
// Declare a sum variable
double sum = 0;
// Sum inside your while loop
sum += x;
// Calculate the nth root of the sum instead
mNroot = pow(sum, (1.0 / mNth));
Add printf commands to see what your variables contain before you check them in your logic statements.
You also need to do something to increment/decrement your variable for your while loop... currently nothing is changing mTotalNums, so it will be an infinite loop.
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
printf("x=%d", x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
mTotalNums--;
}
I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third.
I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component.
The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.).
Can someone point me in the right direction on this? I'd really appreciate any help! :)
It's not clear what you're trying to get as output. You use the example of starting with 3.2, so based from that, and based on your current program, your output is:
KILOMETERS MILES (while loop)
========== =====
1.000 0.620
2.000 1.240
3.000 1.860
Is the problem that your table ends without putting out a value for 3.2? A simple way to solve that (only using loop statements, per your requirement) would be to add the following code:
while (count < km)
{
printf ("%8.3lf %14.3lf\n", km, KM_TO_MILE * km);
count = km;
}
It's really an if statement in disguise, and I don't know if your prof would accept it, but it does provide the final line of output.
Are you required to put out entries that increase by 1.0 (km) for each line? If not, perhaps a better solution is to determine an offset from one line to the next which lets you iterate between 1.0 and km, over a finite number of rows.
A simple solution is multiplying the input (km) by 10, 100 or 1000. Then dividing the result (mi) by the same constant. But avoid printing the result in the loop, take it out of there.
You may lose precision, though (that's your next exercise :)
#include <stdio.h>
#define KM_TO_MILE .62
#define NAMEITHOWYOULIKE 100.0
main (void)
{
double km, mi, count;
printf ("This program converts kilometers to miles.\n");
do
{
printf ("\nEnter a positive non-zero number");
printf (" of kilometers of the race: ");
scanf ("%lf", &km);
getchar();
}while (km <= 1);
km = km * NAMEITHOWYOULIKE;
printf ("\n KILOMETERS MILES (while loop)\n");
printf (" ========== =====\n");
count = 1;
while (count <= km)
{
mi = KM_TO_MILE * count;
++count;
}
printf ("%8.3lf %14.3lf\n", count/NAMEITHOWYOULIKE, mi/NAMEITHOWYOULIKE);
getchar();
}
If you want this for output:
KILOMETERS MILES (while loop)
========== =====
1.000 0.620
2.000 1.240
3.000 1.860
3.200 1.984
Just add the following after your while loop (for an exclusive "final result"):
mi = KM_TO_MILE * km;
printf("%8.3lf %14.3lf\n", km, mi);
or an inclusive "final result" to prevent the last two results being the same if a whole number is used:
while (km > count)
{
mi = KM_TO_MILE * km;
printf("%8.3lf %14.3lf\n", km, mi);
break;
}
You successfully printed the whole number values, but need to print the final value when that is complete. All you need to do at the end (above) is convert the value directly from kilometers to miles.
output image
#include<stdio.h>
int main() {
double kilo, miles, i;
printf("enter the kilometer to be converted :");
scanf("%lf",&kilo);
printf("kilos\t miles\n");
printf("-----------------------------------------------------\n");
i=1;
while(i<=kilo){
miles=i/1.609;
printf("%lf\t %lf\n",i,miles);
i++;
}
}