when i run it and after pressing the second 'n' it doesn't satisfy the logic and the reason is max returns 0(check the last printf) so how can i store the new value in max?
//A GAME FOR GUESSING YOUR NUMBER BY USING THE BINARY SEARCH ALGORITHM
#include <stdio.h>
int main()
{
int min=1;
int max,z,i;
char ans;
printf("\t\t\t***GUESSING GAME***\n");
printf("Let put a rang, the min number is 1, the max is? \n");
scanf("%d",&max);//--> 15
z=(min+max)/2; //the average
while(i<max)
{
dis:
printf("The number is %d? (y/n)\n",z); //--> z =( min(1) + max(15) ) / 2 = 8
scanf("%s",&ans);
if(ans=='n')
{
printf("Is %d too high? (y/n)\n",z);
scanf("%s",&ans);
//new range [1,8]
if(ans=='y')
{
z=(min+z)/2; //--> z =( min(1) + z(8) ) / 2 = 4
goto dis;
}
THIS "
//new range [8,15]
if(ans=='n')
{
z=(z+max)/2; //it should be z =( z(8) + max(15) ) / 2 = 11
goto dis;
}
"
}
if(ans=='y')
{
printf("\\BINGO/");
the value of max will be 0
// printf("max %d z %d",max,z);
}
i++;
}
}
The program has undefined behavior because in the condition of the loop
while(i<max)
{
there is used an uninitialized variable i.
This call
scanf("%s",&ans);
also invokes undefined behavior because there is passed address of one character while the call of scanf tries to read a string. For example if the user enters 'n' scanf write to the addressed memory two characters 'n' and '\0'.
Instead use
scanf(" %c",&ans);
Pay attention to the blank before the conversion specifier %c.
And do not use the goto statement. Instead use a loop.
Related
Want to elicit average of entered real value,until negative value is entered.
My problem is
My calculation don't quit when negative value is entered
It keep asks printf sentence for 3 time.
What did I do wrong?
#include <stdio.h>
int main(void)
{
double total = 0.0;
double input=0.0;
int num = 0;
for (; input >= 0.0;)
{
total += input;
printf("real number(minus to quit):");
scanf_s("%1f", &input);
num++;
}
printf("average:%f \n", total / (num - 1));
return 0;
}
you have many problems with your code :
it's not %1f in the line scanf_s("%1f", &total); as %1f will give you undefined behavior , it's %lfas you are scanning a double , there is a big difference between number one and lower case L
the function called scanf returns an integer indicating how many elements could be assigned to the input that the user entered , so , you should do if(scanf_s("%lf", &input) == 1) to check if the assignment done successfully, that will help you in detecting if - is entered instead of the number
if the user entered a lonely - then sacnf will fail to convert and you have to take another approach
when you are printing the average in this line : printf("average:%f \n", total / (num - 1)); , you actually prints a double , so it's %lf instead of %f
the condition of the for loop is incorrect , you are saying for (; input >= 0.0;) but this will prevent you from entering any negative values as when entering a negative value , the for loop will break , so you could use while(1) instead of the for loop and only break when a - is entered alone
so here is my edited version of yours , I introduced a dummy string to read the buffer and check whether the input was a lonely - or not , and if not then I try to convert it to double and here is my edited solution :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char dummy[30];
double total = 0.0;
int num = 0;
double DecimalConverted = 0;
while(1)
{
printf("real number(minus to quit):");
fgets(dummy, 30, stdin); // gets the input into the buffer
if(dummy[0] == '-' && dummy[1] == '\n') // break from the loop on condition that '-' only entered
break;
// convert the string to decimal
DecimalConverted = strtod(dummy ,NULL);
if(DecimalConverted == 0)
printf("not a number\n");
else{
total += DecimalConverted;
num++;
}
}
printf("average:%lf \n", total / (num - 1));
return 0;
}
and here is the output :
real number(minus to quit):12
real number(minus to quit):-51
real number(minus to quit):-
average:-39.000000
Okay so the prompt was:
"Write a simple program (to demonstrate use of an array) that asks a user to type in numbers and keep typing in numbers until the user enters -1 or the total number of numbers entered reaches 20. Your program will stop asking for new input based on either condition above. Once one of the above conditions are met, the program will output all numbers entered as follows: 1. 888 2. 999 3. 4 …..and so on. Lastly, the program needs to display the sum of all values entered, excluding the -1 used to terminate the user input loop. The array should be used to store the user's inputs, and display them back before the program terminates."
Now, I have most of the prompt completed. It stops at 20 entered variables and displays them and the sum correctly. However, no matter how hard I try, I can't get it to register -1 as an exit. Nor can I get the bulleted list to start from 1. and end at 20. Everything else works just fine.
#include <stdio.h>
#define NUMBER_INPUTS 20
int main(void){
double userInput[NUMBER_INPUTS] = { 0 };
int i = 0;
while (i < NUMBER_INPUTS){
printf("Enter number: \n", i);
scanf("%lf", &userInput[i]);
i++;
}
for(i=0; i<NUMBER_INPUTS; i++)
printf("%i. %.1lf \n", i, userInput[i]);
double total=0;
for(i=0; i<NUMBER_INPUTS; i++)
total+=userInput[i];
printf("Total: %.1lf \n", total);
return 0;
}
This is the code that works just fine. I've tried different do-whiles in different places to register the -1 but it messes up the output list AND doesn't stop the run.
#include <stdio.h>
#define NUMBER_INPUTS 20
int main(void){
double userInput[NUMBER_INPUTS] = { 0 };
int i = 0;
do{
while (i < NUMBER_INPUTS){
printf("Enter number: \n", i);
scanf("%lf", &userInput[i]);
i++;
}
}while (userInput[i] != -1);
for(i=0; i<NUMBER_INPUTS; i++)
printf("%i. %.1lf \n", i, userInput[i]);
double total=0;
for(i=0; i<NUMBER_INPUTS; i++)
total+=userInput[i];
printf("Total: %.1lf \n", total);
return 0;
}
Like this? Just stops at the 20th variable entered. Doesn't matter if I've entered a -1 it just keeps going.
And for the list I attempted to use
i=i+1
to get the list from 1. to 20. to try and bump the i variable up one but for some reason that just shorted the output list to only show 20. and the total? I don't know what I'm doing wrong and would appreciate some input. Thank you.
Be very careful in comparison on floating-point numbers with exact values. (the point of the two links). While double can represent -1 exactly, don't fall into the habit of believing that floating-point numbers can represent any value exactly -- they can't. See: Is floating point math broken? and Why Are Floating Point Numbers Inaccurate?
To stop reading at the input of -1, you need to preserve the value of i (the number of elements) that have a valid double stored when you leave the read loop (that is the number of array elements filled). int n = i; will work (or just use the separate counter n and save i for use as a loop variable). Then in your print loop. for (i = 0; i < n; i++). As you have it, you are attempting to print NUMBER_INPUTS every time. If the user enters -1 after 3 inputs -- that's not going to work.
In order to use any input function correctly, you must validate the return. (this is especially true with scanf with contains many pitfalls for the new C programmer) Otherwise on a matching-failure, your array element will be left indeterminate, character extraction from stdin will cease leaving the offending characters in stdin unread just waiting to bite you again on your next attempted input. Instead -- validate, validate, validate. Lest ye violate Commandment No. 6. Example:
if (scanf ("%lf", &userInput[n]) != 1) { /* validate input */
fputs ("error: invalid double input.\n", stderr);
return 1;
}
Putting the rest together, and giving an example of checking a floating-point value within a tolerance of +/- 1E-5, you could do:
#include <stdio.h>
#define NUMBER_INPUTS 20
int main (void) {
double userInput[NUMBER_INPUTS] = { 0 }, total = 0;
int i = 0, n = 0;
while (n < NUMBER_INPUTS){
fputs ("Enter number: ", stdout);
if (scanf ("%lf", &userInput[n]) != 1) { /* validate input */
fputs ("error: invalid double input.\n", stderr);
return 1;
}
/* check for -1 (with +/- 1E-5 tolerance) */
if (userInput[n] > -1.00001 && userInput[n] < -0.99998)
break;
total += userInput[n];
n++;
}
putchar ('\n');
for(i = 0; i < n; i++)
printf("%d. %.1lf\n", i + 1, userInput[i]);
printf ("\nTotal: %.1lf \n", total);
return 0;
}
Example Use/Output
$ ./bin/total
Enter number: 10
Enter number: 20
Enter number: 30
Enter number: 40
Enter number: 50
Enter number: -1
1. 10.0
2. 20.0
3. 30.0
4. 40.0
5. 50.0
Total: 150.0
Look things over and let me know if you have further questions. You were quite close.
Edit - updated output element indication to i + 1 to meet your requirement of Showing The Numbered List Starting From 1.
I am trying to use "Press 'q' to quit" functionality to exit a do...while loop for calculating the average of a series of user-defined integers. Following several examples I was able to get the exit value to work but it is being included as part of calculating the average.
Example:
quixote#willow:~$ gcc sentinel-borked.c -o sentinel-borked
sentinel-borked.c: In function 'main':
sentinel-borked.c:22:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sum = sum + value;
^
quixote#willow:~$ ./sentinel-borked
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: q
Count is: 3
Average is: 214197589.333333
quixote#willow:~$
I know that the "q" is being treated as an integer, but I'm not sure how to re-write my code to escape it. :(
The simplest workaround that I can think of is to prompt the user for an end point (i.e. "how many integers are you averaging?") and use that, but I would really like to figure this out.
Here is the code I have so far.
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg;
char *value;
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
do {
// Loop through to input values
printf("\nEnter an answer string or q to quit: ");
fgets(value, 10, stdin);
if (value >= 0){
sum = sum + value;
count = count + 1;
}
else {
printf("\nValue must be positive");
}
} while (value[0] != 'q');
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
return 0;
}
EDIT: Replaced screenshot with plain-text inside of a code block. Original image still located at: https://i.stack.imgur.com/qza1N.png
Try this:
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg=0;
char value[10]="";//make value an array or allocate memory for it using malloc and also null initiate it
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
fgets(value,10,stdin);
if(value[strlen(value)-1]=='\n'){//if the user enters a string less than 10 chars a newline will also be stored inside the value array
value[strlen(value)-1]='\0';//you need to remove that \n and replace it with null
}
else{
while((getchar())!='\n');//just removing any extra chars left(when the user enters a string greater than 10 chars)
}
while(value[0]!='q'){//beware it will only check for the first char of the array to be q, anything else will still proceed the loop
sum+=strtol(value,NULL,10);//use this to convert integers inside the array to long ints(many other ways exists)
count++;
fgets(value,10,stdin);//overwrite value each time to get input
if(value[strlen(value)-1]=='\n'){
value[strlen(value)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
if(count==0){
printf("\nAverage is: %lf\n", avg);
}
else{
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
}
return 0;
}
I'm in a beginner C course and I was wondering if there's a way to input integers straight across and averages them together? I'm trying to make my program nice and tidy as possible.
I want to input integers straight across like:
Enter the temperatures and Enter 00 when finished:
60 80 97 42
Average is: 69.75
I don't want to input integers like shown below:
Enter the temperatures and Enter 00 when finished: 75
Enter the temperatures and Enter 00 when finished: 80
Enter the temperatures and Enter 00 when finished: 46
Enter the temperatures and Enter 00 when finished: 91
Average is: 73
#include <stdio.h>
#include <string.h>
int main(void){
char input[64];
double ave = 0.0, value;
int count = 0;
printf("Enter the temperatures and Enter 00 when finished:\n");
while(1){
if(1==scanf("%63s", input)){
if(strcmp(input, "00") == 0)
break;
if(1==sscanf(input, "%lf", &value))
ave += (value - ave) / ++count;
}
}
if(count)
printf("Average is: %g\n", ave);
else
printf("Input one or more values\n");
return 0;
}
Using the scanf function any white space character is seen as the end of input for each integer. Thus using scanf within a loop you can continuously input values within the same line.
If you want it to work for a different number of entries each time you must modify the code to use a while loop and have a dynamically allocated array, since the size is unknown. Then check for an escape sequence like 00.
All the values are stored into an array where you can do the averaging calculations
#include <stdio.h>
#define NUM_OF_ENTRIES 5
int main()
{
printf("Enter numbers: ");
int i = 0;
int value_set[NUM_OF_ENTRIES];
for (i = 0; i < NUM_OF_ENTRIES; i++ )
{
scanf("%d", &value_set[i]);
}
I believe that you shall change your terminating condition from enter 00 to something like enter x.
So, your code shall look like this::
int n;
int sum = 0, count = 0;
while(scanf("%d", &n)) {
sum = sum + n;
count++;
}
printf("%lf", double(sum/count));
scanf returns the number of successfully taken inputs. Since n is declared as int, so everytime you enter some integer value, scanf will return 1 and if you enter some value which is not of type int like if you enter x (which is a char) scanf will return 0, because x is not an integer, and this way you can calculate the average.
Code can use scanf("%d", &number) to read an integer. The trouble is that "%d" first scans and discards leading white-space which includes '\n' before scanning for an int. '\n' is needed to know when to stop as OP wants "input integers straight across". So instead code should look for white-space one character at a time first. Upon finding the end-of-line '\n', scanning is complete.
With this approach there are no practical limits to the count of numbers.
#include <ctype.h>
#include <stdio.h>
double Line_Average(void) {
double sum = 0;
unsigned long long count = 0;
while (1) {
int ch;
while (isspace(ch = fgetc(stdin)) && ch != '\n')
;
if (ch == '\n' || ch == EOF) {
break; // End-of-line or End-if file detected.
}
ungetc(ch, stdin); // Put back character for subsequent `scanf()`
int data;
if (scanf("%d", &data) != 1) {
break; // Bad data
}
sum += data;
count++;
}
return sum/count;
}
// sample usage
puts("Enter the temperatures");
double Average = Line_Average();
printf("Average is: %.2f\n", Average);
One possibility:
double sum = 0;
double val;
size_t count = 0;
char follow;
while( scanf( "%lf%c", &val, &follow ) == 2 )
{
sum += val;
count++;
if ( follow == '\n' )
break;
}
printf( "average = %f\n", sum/count );
This will read each number plus the character immediately following, until it sees a newline or a non-numeric string. It's not perfect; if you type a number followed by a space followed by a newline, then it won't break the loop. But it should give you some ideas.
since u did not post the code. i have given a sample code... from here u can build what u require with some tweaks
#include<stdio.h>
main()
{
int one, two, thr, four, five, avg;
printf("\nEnter the temperatures and Enter 00 when finished:");
scanf ("%d %d %d %d %d", &one, &two, &thr, &four, &five);
avg=(one+two+thr+four+five)/5;
printf("Average value is %d", avg);
}
So I'm doing this problem where I need to calculate the average using pointers and without using strings. The user will input a letter and then a space followed by a number(an integer), the letter indicating if the number is positive(p) or negative(n) or if the user is done input-ing numbers(e).
I know I need a loop to continually read in number and add or subtract them from the sum until the letter "e" is input.
program should have and use the following function
// Precondition: value will be a pointer to where the input value is to be stored.
// Postcondition: returns true if a number was read, or false if
// it was the end of the list. The int pointed to by value will be
// set to the number input by this function, made negative or
// positive depending on the character before it. int read_number(int* value);
A sample input being p 20 p 20 p 10 p 10 e
output: 15
My problem as of now is my loop is only reading for two cycles of input, and even then it isn't printing the average. Also I'm supposed to use a pointer but given the directions i'm still not sure what the context is, I'm not seeing where a pointer is useful.
#include <stdio.h>
//precondition: value will be a pointer to where the input value is to be stored.
int main(){
int sum;
int num;
int counter;
float avg;
char let;
scanf("%c %d", &let, &num);
for (counter=0;let == 'n' || let == 'p'; counter++){
scanf("%c %d", &let, &num);
if ( let == 'n'){
sum-=num;
}
if (let == 'p'){
sum+=num;
}
if ( let == 'e'){
avg=sum/counter;
printf("%f", &avg);
}
}
return 0;
}
Your input is:p 20 p 20 p 10 p
10 e.
The scanf before the loop scans 'p' and then skips the space and then scans 20. The next scanf in the loop reads the space as it is also a character and the %d fails to scan an int and the stops scanning. See the problem?
To fix it, change
scanf("%c %d", &let, &num);
To
scanf(" %c %d", &let, &num);//Note the space before %c
The space before %c gobbles up whitespace characters(if any) like newlines, spaces etc until the first non whitespace character.
Other problems include not initializing sum to 0 and using &avg instead of avg in the printf below
printf("%f", &avg);