I'm writing a program that asks the user to input the high and low temperatures over the course of three days. The high temperature for each day has to be greater than the low, the high must not be greater than 41 and the low must not be less than negative -41.
I wrote a while statement following the inputs for the first day however, I get the error comparison between pointer and integer.
I figured it had something to do with me using a set integer so I tried just making a while statement that involved high being greater than low, which resulted in the program working, but I found the while loop was skipped entirely. Here's my code so far:
Edit: I'm beginning to understand where my while loop went wrong. I believe it was because I neglected to assign a value from the array to the high and low and I also neglected to have the code rerun if the user met the conditions for the while loop. Initially, I had wrote it so the high and low held no value and the while condition was trapped in an infinite loop because I did not give it something to execute following the conditions being met.
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
int max = 40;
int min = -40;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low);
while (high[0] > max || low[0] > min || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
return 0;
}
The high temperature for each day has to be greater than the low, the
high must not be greater than 41 and the low must not be less than
negative -41.
i have modified your code and written comment also to understand :
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 41;
const int MIN = -41;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]); //address of first element
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]); //address of first element
/*Check for User Input Value*/
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
//TODO-:/*Check for User Input Value*/
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
//TODO-:/*Check for User Input Value*/
//TODO-:/*Print the all value*/
return 0;
}
Todo part you can complete by taking reference from other part of code.
Related
I wrote a program which takes three numbers from the user and prints out the maximum number, but when I run the program it is not taking the numbers from the user correctly
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, num2, num3;
printf ("PROGRAM TO FIND THE BIGGEST NUMBER\n");
printf ("\n");
printf ("enter first number : ");
scanf ("%d ",&num1);
printf ("enter second number : ");
scanf ("%d ",&num2);
printf ("enter third number : ");
scanf ("%d ",&num3);
printf("%d - %d - %d \n",num1,num2,num3);
if (num1>num2 && num1>num3){
printf ("the biggest number is %d",num1);
}
else if (num2>num1 && num2>num3){
printf ("the biggest number is %d",num2);
}
else if (num3>num1 && num3>num2){
printf ("the biggest number is %d",num3);
}
return 0;
}
Remove the space after the %d in all the scanf calls. The space will match any character including the newline. The scanf will keep reading until the match fails. By removing the space the match fails when the newline character is entered and the code continues.
I have written a program that asks the user the input the high and low temperature over the course of four days. Following this, the program calculates the mean temperature using the inputs from all four days. Everything is working fine however, I need to have the program determine and output the greatest high temperature and the day it occurred on as well as the smallest low temperature and the day it occurred on. Here's my code so far
#include <stdio.h>
#define NUMS 4
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int totalhigh;
int totallow;
int sum;
float avg;
printf ("---===IPC Temperature Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
while (high[1] > MAX || low[1] < MIN || high[1] < low[1]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
}
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
}
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
while (high[3] > MAX || low[3] < MIN || high[3] < low[3]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
}
totalhigh = high[0] + high[1] + high[2] + high[3];
totallow = low[0] + low[1] + low[2] + low[3];
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
if (high[0] > high[1] || high[0] > high[2] || high[0] > high[3]) {
printf ("The highest temperature was %d, on day 1\n", high[0]);
}
else if (high[1] > high[0] || high[1] > high[2] || high[1] > high[3]) {
printf ("The highest temperature was %d, on day 2\n", high[1]);
}
else if (high[2] > high[0] || high[2] > high[1] || high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
return 0;
}
Your current code can use a loop and a helper function, which would shorten your code by reducing all those scanf() calls. You could also abstract a lot more, by using more functions, but it will show the general idea.
It is also good to check the result of scanf(), just in case the user enters a non-integer.
Your current code could look like this:
#include <stdio.h>
#include <stdlib.h>
#define NUMS 4
/* takes a pointer to a number */
void get_input(int *temp) {
if (scanf("%d", temp) != 1) {
printf("Invalid temp entered\n");
exit(EXIT_FAILURE);
}
}
int main(void) {
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int day = 1, totalhigh = 0, totallow = 0, sum;
float avg;
for (size_t i = 0; i < NUMS; i++) {
printf ("Enter the high value for day %d: ", day);
/* takes the address of the pointer given by get_input() */
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
while (high[i] > MAX || low[i] < MIN || high[i] < low[i]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day %d: ", day);
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
}
day++;
}
for (size_t i = 0; i < NUMS; i++) {
totalhigh += high[i];
totallow += low[i];
}
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
return 0;
}
In terms of finding the largest and smallest temperatures, here is a method you can use:
Set max and min to the first element of your array, array[0].
loop from i=1 to i=n.
If and element if bigger than max, set max to array[i]. If an element is smaller than min, set min to array[i].
The day for the highest and lowest temperatures will be i+1.
Since doing something like this will help you understand loops better, I decided to just describe the steps. The above code was just an improvement on your current code, and showing you a easier way to do it will show you a different perspective on how to do problems like these.
I updated my code to have the if statement mentioned in my above code to function correctly. Here it is:
if (high[0] > high[1] && high[0] > high[2] && high[0] > high[3]) { // Check to see if day 1 has the highest temperature against days 2,3 and 4.
printf ("The highest temperature was %d, on day 1\n", high[0]); // Output day 1 as the highest temperature and indicate the temperature value.
}
else if (high[1] > high[0] && high[1] > high[2] && high[1] > high[3]) { // Same function as the above function for day 1 except this is used for day 2.
printf ("The highest temperature was %d, on day 2\n", high[1]); // Refer to day 1 printf
}
else if (high[2] > high[0] && high[2] > high[1] && high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
// Switch out high values with low values in order to determine lowest temperature and its corresponding day.
Im a beginner to C and I'm having trouble with structs.
after I've asked user for all attributes, id like to print all the values of the struct. The problem is that after I've got input all the attributes to a struct and it loops back again to ask for attributes a second time, the first struct input gets replaced by the second struct input.
I'm pretty sure that I'm allocating the same memory space over and over and thus causing the problem but I'm stuck on how to fix it. Id appreciate any advice on what i can do. thanks!
case 2:
printf ("Please input a SKU number:");
scanf ("%d", &item[MAX_ITEMS].sku_);
printf ("Quantity:");
scanf ("%d", &item[MAX_ITEMS].quantity_);
printf ("Price:");
scanf ("%f", &item[MAX_ITEMS].price_);
printf ("The item is successfully added to the inventory");
break;
to print out the sku, quantity and price
switch (menuSelection) {
case 1:
printf ("Inventory\n");
printf ("=========================================\n");
printf ("Sku Price Quantity\n");
for (i =0 ; i<=MAX_ITEMS; i++){
printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
}
printf ("=========================================\n");
break;
here is my whole code:
#include <stdio.h>
#define MAX_ITEMS 10
struct Item{
int sku_;
float price_;
int quantity_;
}item[MAX_ITEMS];
int main (void) {
int size=0;
int menuSelection;
int i=0;
printf ("Welcome to the Shop\n");
printf ("===================");
do {
printf ("\nPlease Select from the following options:\n");
printf ("1) Display the inventory.\n");
printf ("2) Add to shop.\n");
printf ("0) Exit.\n");
printf ("select:");
scanf ("%d", &menuSelection);
if (menuSelection <0 && menuSelection >2){
printf ("Invalid input, try again: Please select from the following options:");
}
else {
switch (menuSelection) {
case 1:
printf ("Inventory\n");
printf ("=========================================\n");
printf ("Sku Price Quantity\n");
for (i =0 ; i<=MAX_ITEMS; i++){
printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
}
printf ("=========================================\n");
break;
case 2:
printf ("Please input a SKU number:");
scanf ("%d", &item[size].sku_);
printf ("Quantity:");
scanf ("%d", &item[size].quantity_);
printf ("Price:");
scanf ("%f", &item[size].price_);
printf ("The item is successfully added to the inventory");
break;
case 3:
break;
}
}
} while (menuSelection != 0);
return 0;
}
You create an array of Item objects with the length of MAX_ITEMS, currently being 10. That is, your objects have the indices of 0 to 9. Yet when asking the user for input, you always store the data at item[MAX_ITEMS] which is out of bounds of your array.
As a side note, when printing your array, you always print it whole, meaning also uninitialised items.
You have to store how many items are already "added to the shop" and use this number to determine the next array index where user input has to be stored. When printing you only have to iterate over the items already stored. Don't forget bounds checking, e.g. don't allow new user input when your shop is full.
The problem is that you always save the new values in the same place:
item[MAX_ITEMS].sku_
Instead, you should have a counter that show how many items are stored and save the new values in the place that is equal to the counter:
item[counter].sku_
and after every insertion you should increase the counter:
counter++;
So, your code should look like this:
int counter=0;
...
case 2:
printf ("Please input a SKU number:");
scanf ("%d", &item[counter].sku_);
printf ("Quantity:");
scanf ("%d", &item[counter].quantity_);
printf ("Price:");
scanf ("%f", &item[counter].price_);
printf ("The item is successfully added to the inventory");
counter++;
break;
I hope I was helpful
The item you defined is a array with size of MAX_ITEMS, so the problem of you is not about struct but array.
In most of computer programming language, indexing an array should use a offset start on zero. That is, MAX_ITEMS of item[MAX_ITEMS] is out of range for the array, you got a bug and do not find it. When you adding a item to your shop, you should code like this:
case 2:
if (last < MAX_ITEMS - 1)
{
printf ("Please input a SKU number:");
scanf ("%d", &item[last].sku_);
// ...
last ++; // on success
}
else
{
print("oops, shop is full.");
}
#include <stdio.h>
#include <conio.h>
int main(void)
{
int year;
float principal, amount, inrate, period, value;
printf ("Please enter principal");
scanf ("%f", principal);
amount = principal;
printf ("Please enter interest rate");
scanf ("%f", inrate);
year = 0;
printf ("Please enter period");
scanf ("%f", period);
while(year <= period)
{printf ("%d %f\n", year, amount);
value = amount + amount*inrate;
year = year + 1;
amount = value;
}
getch();
return 0;
}
I tried running this code but I have no output at all. There are 0 warnings and messages. Frankly, I don't know if the code will serve the intended purpose without being able to run it! Please help.
I tried running this code but I have no output at all
Really? I got 6 warnings and a segfault! what compiler are you using?
||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
main.cpp||In function 'int main()':|
main.cpp|8|warning: format '%f' expects argument of type 'float*', but argument 2 has type 'double' [-Wformat]|
main.cpp|11|warning: format '%f' expects argument of type 'float*', but argument 2 has type 'double' [-Wformat]|
main.cpp|14|warning: format '%f' expects argument of type 'float*', but argument 2 has type 'double' [-Wformat]|
main.cpp|8|warning: 'principal' is used uninitialized in this function [-Wuninitialized]|
main.cpp|11|warning: 'inrate' is used uninitialized in this function [-Wuninitialized]|
main.cpp|14|warning: 'period' is used uninitialized in this function [-Wuninitialized]|
||=== Build finished: 0 error(s), 6 warning(s) (0 minute(s), 0 second(s)) ===|
The code looks like some sort of interest calculator (https://en.wikipedia.org/wiki/Interest)
try that code:
#include <stdio.h>
#include <conio.h>
int main(void)
{
int year;
float principal, amount, inrate, period, value;
printf ("Please enter principal ");
scanf ("%f", &principal);
amount = principal;
printf ("Please enter interest rate ");
scanf ("%f", &inrate);
year = 0;
printf ("Please enter period ");
scanf ("%f", &period);
while(year <= period)
{
printf ("%d %f\n", year, amount);
value = amount + amount*inrate;
year = year + 1;
amount = value;
}
getch();
return 0;
}
scanf reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. So if you want to save something in the variable with scanf, you should give pointer as argument with &.
After adding the & address-of before the variable arguments in the scanf() calls, it works. But I didn't check the arithmetic.
#include <stdio.h>
#include <conio.h>
int main(void)
{
int year;
float principal, amount, inrate, period, value;
printf ("Please enter principal ");
scanf ("%f", &principal); // <-- added &
amount = principal;
printf ("Please enter interest rate ");
scanf ("%f", &inrate); // <-- added &
year = 0;
printf ("Please enter period ");
scanf ("%f", &period); // <-- added &
while(year <= period) {
printf ("%d %f\n", year, amount);
value = amount + amount*inrate;
year = year + 1;
amount = value;
}
getch();
return 0;
}
The problems you are having are twofold. The first, scanf requires a pointer to store values. (e.g. scanf ("%f", principal); should be scanf ("%f", &principal);)
Another issue to be aware of is reading values with scanf will leave a newline '\n' in the input buffer stdin each time you press [Enter]. scanf will read the number you enter, but leave the newline in stdin. The next time you call scanf it sees the newline (value: 0xa hex, 10) in stdin and reads that as the next value.
Note: in this case, %f will skip the newline, so it is not necessary. However, be aware that decimals or strings read by scanf will be effected. Always keep this in mind when using scanf.
If faced with scanf seeming to skip over expected input, a simple solution is the flush (empty) the input buffer. (an example of how to handle this is provided in function flush_stdin below). Simply call flush_stdin after each call to scanf where this is a potential problem.
#include <stdio.h>
// #include <conio.h>
void flush_stdin ()
{
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
int main(void)
{
int year = 0; /* Always INITIALIZE your variables */
float principal, amount, inrate, period, value;
principal = amount = inrate = period = value = 0;
printf ("Please enter principal: ");
scanf ("%f", &principal);
amount = principal;
printf ("Please enter interest rate: ");
scanf ("%f", &inrate);
year = 0;
printf ("Please enter period: ");
scanf ("%f", &period);
while(year <= period)
{
printf ("%3d %10.2f\n", year, amount);
value = amount + amount*inrate;
year = year + 1;
amount = value;
}
// getch();
return 0;
}
Output
$ ./bin/scanf_noop
Please enter principal: 123.45
Please enter interest rate: .05
Please enter period: 24
0 123.45
1 129.62
2 136.10
3 142.91
4 150.05
5 157.56
6 165.43
7 173.71
8 182.39
9 191.51
10 201.09
11 211.14
12 221.70
13 232.78
14 244.42
15 256.64
16 269.48
17 282.95
18 297.10
19 311.95
20 327.55
21 343.93
22 361.12
23 379.18
24 398.14
i have written the following program however every time i run it, the for loops do not work until i enter another number. The for loops then run, using the second number entered. why is this happening? no one seems to be having this problem... here is the program:
#include <stdio.h>
#include <math.h>
int main(void)
{
float limit;
float count;
float series1, series2;
printf("Enter a limit for the series ");
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
{
for (series1 = 1, count = 2; count <= limit; count++)
series1 += 1.0/count;
printf ("\nThe sum of the first infinite series is %.4f", series1);
for (series2 = 1, count = 2; count <= limit; count++)
series2 += (1.0/count) * pow ((-1),(count - 1));
printf ("\nThe sum of the second infinite series is %.4f", series2);
printf("\n\nEnter a limit for the series (q to quit) ");
scanf ("%f", &limit);
}
return 0;
}
Your problem is right here:
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
The while loop is going to execute that scanf everytime it starts, so just lose the first scanf.
When you run the while loop while (scanf ("%f", &limit) == 1) it is running scanf ("%f", &limit) == 1 again, after you have already ran it. Try setting the first scanf to output a variable and run the variable in the while loop.