I need to print the sum and average of user input array. So if user inputs 2,4,6,9,10 it should print 6.
However, after the loop ended my printf is not printing anything.
Even if I put the printf inside the array it only prints out 0.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double num[6],average, sum=0, closest;
printf("Enter 6 doubles\n");
for (i=0; i<6; i++)
{
scanf("%lf",&num[i]);
sum += num[i];
}
average = sum/i;
printf("Average %d", average);
}
There are a few things you need to do in the code. You should be making sure they enter 6 numbers (in your opening post you only list 5, this will create problems). I changed the printing to use this and stripped out some variables that you don't use.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double sum = 0;
printf("Enter 6 doubles\n");
for (i = 0; i < 6; i++)
{
double value;
scanf("%lf", &value);
sum += value;
}
printf("Average = %f", sum / i);
}
Enter 6 doubles:
2 4 6 9 10 10
Average = 6.833333
This question is not a duplicate but I found the answer on StackOverflow here
The stdout stream is buffered, so will only display what's in the
buffer after it reaches a newline (or when it's told to). You have a
few options to print immediately:
Print to stderr instead using fprintf:
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush:
printf("Buffered, will be flushed"); fflush(stdout); // Will now print everything in the stdout buffer
You can also disable buffering
on stdout by using setbuf:
setbuf(stdout, NULL);
Then regarding your code, here are a few remarks:
As described in man 3 printf the conversion specifier f already convert to double floating point values, so no need for a length modifer flag.
The average value is also a double so if you print it as an integer %d you will lose the real valued part, consider using %f as well.
the following proposed code:
uses a proper signature for main()
corrects the format used in the call to printf()
appends a '\n' to the format string in 'printf()' so the data is immediately output rather than after the program exits
gives 'magic' numbers (I.E. 6) meaningful names
properly checks for I/O errors and handles any such error
eliminates unneeded variables
does not include header files those contents are not used
documents why each header file is included
properly limits the scope of local variable 'i'
cleanly compiles
performs the desired functionality
and now, the proposed code:
#include <stdio.h> // printf(), scanf(), perror()
//#include <math.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_ENTRIES 6
int main( void )
{
//int i;
// double num[6];
double num;
double average;
double sum=0.0;
// double closest;
printf("Enter %d doubles\n", MAX_ENTRIES );
for (int i=0; i< MAX_ENTRIES; i++)
{
if( scanf( "%lf", &num ) != 1 )
{
fprintf( stderr, "scanf for number failed\n" );
exit( EXIT_FAILURE );
}
sum += num;
}
average = sum / MAX_ENTRIES;
printf("Average %f\n", average);
}
a typical run of the code results in:
Enter 6 doubles
1.0
2.0
3.0
4.0
5.0
6.0
Average 3.500000
Related
I am attempting to create a text file using C that will contain a table of values in Fahrenheit and their Celsius conversion.
I am able to use fprintf properly outside of the for loop but when I put it inside it does not print anything to the file. The code compiles properly but when I try to execute it completes but with exit code "-1073741819"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
FILE *filePointerThree;
double myArray[100];
filePointerThree = fopen("myFileFive.txt", "w");
for(int i=0; i<=100; i++)
{
myArray[i] = (i-32)/1.8;
}
for(int j=0; j<=100; j+=5)
{
fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, myArray[j]);
}
fclose(filePointerThree);
}
Your array needs to be larger to hold 101 values (0 through 100):
double myArray[101];
Upon further review, the code can be simplified to not require an array, as follows. A return 0; at the end of main() will ensure an exit code of 0. Minor: the math.h and stdlib.h includes are not required as fopen() and friends are defined in stdio.h.
#include <stdio.h>
int main()
{
FILE *filePointerThree;
filePointerThree = fopen("myFileFive.txt", "w");
for(int j=0; j<=100; j+=5)
{
fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, (j-32)/1.8);
}
fclose(filePointerThree);
return 0;
}
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
for our homework we have to compile the program we wrote in the school. I have typed it without mistakes(verified with my colleagues) and the program does not work, I am using DEV C++ and the error log says, file not recognized: File format not recognized.
I tried using integer and not double but it stays the same...I have no idea what is wrong.
#include <stdio.h>
#define VELIKOST 23
int main (void)
{
double dPolje[VELIKOST];
int iStevec,iVecje=0;
printf("Algoritem, ki določi koliko elementov podatkovnega polja imajo vrednosti vecje ali enake od 10 \r\n");
for(iStevec=0;iStevec<VELIKOST;iStevec++)
{
printf("Vnesite %i. stevilo:",iStevec=iStevec+1);
fflush(stdin);
scanf("%lf",&dPolje[iStevec]);
if(dPolje[VELIKOST]>=10)
{
iVecje++;
printf("Element dPolje [%i]=%f.",iStevec,dPolje[iStevec]);
}
printf("%i elementov polja je imelo vecje ali enako vredost 10.",iVecje);
return(0);
}
}
I'm guessing that Dev C++ doesn't support Slovenian.
Create a new file and try this code:
#include <stdio.h>
#define SIZE 23
int main(){
double dField[SIZE];
int i, larger = 0;
printf("This algorithm, determines how many data field items have values greater than or equal to 10.\n");
for (i = 0; i < SIZE; i++){
printf("Enter field number %i:", i + 1); //Note I fixed this original code had i = i + 1
//fflush(stdin); unneeded
scanf("%lf", &dField[i]);
if (dField[i] >= 10){
larger++;
printf("Field number %i = %lf", i, dField[i]);
}
} //Moved this above final output and return
printf("%i field items were greater than or equal to 10 ", larger);
return 0;
}
I expect that to work.
Either way I'd definitely change compilers. Visual Studio Community Is a great fully featured IDE.
I have a text file containing single precision data, such as
0.123456 0.123456 0.123456
I want to read it in C using following syntax:
FILE *myfile.
double c[4];
int i=0;
c[0]=1;
myfile=fopen(...)
for (i=1;i<=3;i++) {
fscanf(myfile, "%lf", &c[i]);
}
What I print is a huge number that is obviously wrong.
Any one can solve this problem?
Ps: I have edited my problems after I viewed the answers.
here is my more information:
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
FILE *file_params;
int main() {
double *delx;
int i;
file_params=fopen(filename,"r");
delx = (double *) malloc ((4)*sizeof(double));
delx[0]=0;
for(i=1; i<=3; i++) fscanf(file_params, "%lf", &delx[i]);
for(i=1; i<=3; i++) printf("%lf", delx[i]);
return 0;
}
Responding to the version of code that appears as I write ...
Remove #include <windows.h>
Change filename to be the name of a file that exists
Check that file_params != NULL and delx != NULL before proceeding
Check the return value of fscanf, e.g. if ( 1 != fscanf(file_params, "%lf", &delx[i]) ) { printf("fscanf failed\n"); exit(EXIT_FAILURE); }
Change printf("%lf", to printf("%f ",
Program works.
What I print is a huge number that is obviously wrong.
Possibly you are seeing the numbers all next to each other without spaces (since you didn't printf a space) and didn't realize what you were seeing.
Array indexes start at 0. You started at 1.
for loop should be
for (i=0;i<3;i++)
fscanf(myfile,"%lf",&c[i]);
I see the following errors:
Use %lf instead of lf%.
Use &c[i] instead of &c.
In the for- loop, use,
for (i=0;i<3;i++) {
instead of
for (i=1;i<=3;i++) {
In summary,
for (i=0;i<3;i++) {
fscanf(myfile, "%lf", &c[i]);
}
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.