Hi I am wondering why my code is not working. Here are the instructions for it: Suppose we want to determine the largest number of a series of non-negative real values entered by the user. The user repeatedly enters the values, one at a time, and finally enters the value −1 to indicate that there are no more values to enter. We then print the largest value entered by the user, on the screen. If the first number entered by the user is −1 (i.e., the user enters no non-negative values), then we’ll print the message “Error: no data!” on the screen. (Your program doesn’t have to verify that the numbers are non-negative.).
Now here is my code. For reference, some combinations of numbers work such as 5 5 5 5 -1, and 1 2 3 4 5 10 -1. Other combinations don't work such as 1 -1, 1 2 2 3 4 5 10 -1.
#include <stdio.h>
#include <stdlib.h>
#define SENTINEL -1
int main( void ) {
double value = 0;
double value2 = 0;
double large = 0;
printf("enter your values: ");
scanf("%lf %lf", &value, &large);
if (value==SENTINEL){
printf ("Error: no data!");
}
else{
while(value!=-1){
printf("enter value: ");
scanf("%lf", &value2);
if (value2>value){
large = value2 ;
}
value = value2;
}
printf("%f\n", large );
}
return 0;
}
CodePudding user response:
I did not see C language for a long time, but I think that something like this might work:
double value = SENTINEL;
double large = SENTINEL;
printf("enter your values: ");
while (scanf("%lf", &value) != -1) {
if (value > large)
large = value;
if (value == SENTINEL)
break;
}
if (large == SENTINEL)
printf("Error no data\n");
else
printf("%lf \n", large);
return 0;
CodePudding user response:
Try something like this:
#include <stdio.h>
#include <stdlib.h>
#define SENTINEL -1
int main(void)
{
double value = 0;
double maxval = -1.0;
int count = 0;
int stat;
while (value != SENTINEL) {
printf("Enter a values (-1 when done)");
do {
printf(": ");
stat = scanf(" %lf ",&value);
} while (stat != 1);
if (value != SENTINEL) {
if (value > maxval)
maxval = value;
count ;
}
}
if (count == 0)
printf ("Error: no data!");
else
printf("%f\n",maxval);
return 0;
}
CodePudding user response:
To help you, try to print values you read.
It seems you use double and you compare it to an int (-1).
If numbers given are only integers use the according variable type.
