Invalid operands to binary & (have 'float *' and 'float') - c

I can't figure out what I need to do to get my code to work, I've tried a few things but the same error keeps occurring. I'm not sure how else to proceed, the main issue of the code appears to be converting the hours and minutes into only hours. I know this is a very basic question, but I'm a beginner and I can't seem to get a solution.
// freezer.c
// Estimates the temperature in a freezer given the elapsed time since a power failure.
#include <stdio.h>
#include <math.h>
int main(void) {
float dec_time, // input - time in hours and minutes.
temperature, // output - temperature in degrees celsius
hours, // input for dec_time
minutes; // input for dec_time
/* Get the time in hours and minutes */
printf("hours and minutes since power failure: ");
scanf("%lf%lf", &hours &minutes);
/* Convert the time in hours and minutes into only hours in real number */
dec_time = hours + (minutes / 60.0);
// Using time via an equation to estimate the temperature
temperature = ((4 * dec_time * dec_time) / (dec_time + 2)) - 20;
// Display the temperature in degrees celsius
printf("Temperature in freezer %9.2f.\n", temperature);
return 0;
}
Any explanation anyone can give to give me insight on this would be greatly appreciated.
Edit: when I added the comma to the scanf() statement in the code on my computer, the primary compilation error in the title was resolved. I also changed the %lf to %f, but now when I key in a single digit to a.out, e.g. 3, the program does not compute until I key in q!.

Change scanf("%lf%lf", &hours &minutes) to scanf("%f%f", &hours, &minutes). No 'l', #melpomene add comma #Anton Malyshev.
Also recommend to check result to see if it is 2. (2 fields successfully scanned).
if (2 != scanf("%f%f", &hours, &minutes)) {
puts("Input error");
exit(1);
}

scanf("%lf%lf", &hours &minutes);
^ comma needed
You missed a comma ,.
Re-write as follows-
scanf("%f%f",&hours,&minutes); // make sure you use only %f and not %lf

You missed comma, that's how it should be: scanf("%lf%lf", &hours, &minutes)

Related

Code is ignoring IF command in C, Issues with FOR

I had posted on here before, but I was never able to get the help I needed.
I'm working on a school project and I can not get my program to work properly.
The program should prompt the user to enter the number of gallons used and
the number of miles driven for each of the 3 tanks of gas. The program should
then calculate and display the miles per gallon obtained for each tank. Once
processing is complete for the 3 tanks, the program will calculate the overall
mileage(total gallons / total miles) and display a friendly "Goodbye" message.
The issue i am having is that I can not get it to display to OVERALL Millage. it ends after looping 3 times.
I know different loop statements need conditions to be met, but I cant get the FOR loop to work properly. Im getting really frustrated, cause I know this should not be this hard.
Code
#include <stdio.h>
int main(void)
{
int miles,i=3;
float gallons, mg, overall = 0, avg = 0;
while(i>0)
{
printf("Enter the gallons used: ");
scanf("%f", &gallons);
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;i--;
}
if(gallons == 0)
{
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
return 0;
}
If I read your code correctly, then what is preventing the overall mileage from being printed is the following final if statement:
if (gallons == 0)
If you remove it, then the overall mileage should print. Use this pattern:
while (i > 0)
{
// your while loop here
}
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
This if (if (gallons == 0) {})block is out of while loop.
First, you need to move the if loop inside while loop.
and this if condition should be for variable i as follow and not for gallons.
if (i == 0)
{
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
}
In this case, after 3 iteration, value of i will be 0 so it will enter into the if block and calculate and print the overall miles/gallon.
Adding to Tim Biegeleisen's answer:
mg = miles/gallons;
What if gallons equals to 0? e.g. 0 miles for 0 gallons
This will lead to floating point exception.
A simple if-else can solve this problem!
if(!gallons)
mg = 0;
else
mg = miles/gallons;

Unexpected behavior from beginner C program

I am working to learn about computing at a more granular level and have started studying both Linux and C at the same time. Smooth sailing until just now.
I am running Linux Mint 17 on Kernel 3.16.0-38-generic and using Code::Blocks 13.12 as my IDE.
The following pastes are my practice code using data types, variables, and printf(), and the associated output I see in a vt -- the oddity I see is that on my experimentation with decimal places using the float data type, it seems to be skipping values after the 5th and eventually 4th decimal place.
Am I abusing the process of calling a variable, am I missing a bug in my code, or is this a bug in CodeBlocks? Also -- I'm not sure why my code snippet is completely mashed together in the preview, so my apologies for the poor readability
code to be compiled and executed:
/* Prints a message on the screen */
#include <stdio.h>
echar a1 = 'a';
int i1 = 1;
float f1 = 0.123456;
int main()
{
printf("Testing %c la%sof characters using variables \n", a1, "rge string " );
printf("This line has the values %d and %f.\n", i1, f1);
printf("%f can also be displayed as %.5f or %.4f or %.3f or %.2f or %.1f or %.0f \n",
f1, f1, f1, f1, f1, f1, f1);
printf("Which is an integer . . .");
return 0;
}
output of compiled and executed code
Testing a large string of characters using variables
This line has the values 1 and 0.123456.
0.123456 can also be displayed as 0.12346 or 0.1235 or 0.123 or 0.12 or 0.1 or 0
Which is an integer . . .
Process returned 0 (0x0) execution time : 0.002 s
Press ENTER to continue.
Thank you for any help you can provide. I am studying from C Programming Absolute Beginner - by Greg Perry
As was mentioned in the comments, the last digit is being rounded.
If you had this:
float f1 = 0.777777;
The output would be this:
This line has the values 1 and 0.777777.
0.777777 can also be displayed as 0.77778 or 0.7778 or 0.778 or 0.78 or 0.8 or 1
Similarly, if you had this:
float f1 = 0.999888;
You'd get this:
This line has the values 1 and 0.999888.
0.999888 can also be displayed as 0.99989 or 0.9999 or 1.000 or 1.00 or 1.0 or 1

Scanning multiple inputs and outputting based on the amount true/false - in C

I have an assignment that is supposed to ask the user a few questions about temperature in regards to a plane launch.
EX:
What is the average temperature?
Lowest temperature in the past day?
Is it raining?
Now the program is suppose to take the input and base it on a few conditions
temperature must be 42 degrees
temperature couldn't have dropped below 32
Can't be raining
So I got the output that gives 'the okay' for the plane launch by nesting some 'if statements', that's all good. The problem is that, depending on the number of incorrect statements, it'll output something different.
EX:
If the only issue is that the temperature is below 32 degrees, it'll output:
"The plane is not launching because the temperature has dropped below 32 degrees in the past day"
If the temperature dropped below 32 degrees AND it's raining, the program will spit out
"The plane is not launching because:
The temperature is below 32 degrees
it's raining"
I know that I can make a whole bunch of if statements for each situation but that'll just make my code massive and confusing. Surely there must be a simpler way to set it up in which 'there are 2 statements false, so print this depending on which 2'. Should I make a switch statement?
The last class I took I separated all of the work into functions and then just called down each one into the main when needed. In this course, we have to do all of the work in the main function and it is kinda confusing because I began learning a different way.
Thanks in advance.
The ternary operator combined with format strings is a handy way to solve this problem.
The ternary operator allows you to conditionally-assign a value based on some boolean expression, and format strings let you inject other strings into your printfs, even empty strings:
char *cond1 = temperature_is_low ? "the temperature is low" : "";
char *cond2 = is_raining ? "it's raining" : "";
char *sep = (temperature_is_low && is_raining) ? " and " : "";
printf("The plane will not launch because %s%s%s.\n", cond1, sep, cond2);
If you can't use ternary operators or format strings, you could do the same thing by separating the print over multiple lines:
printf("The plane will not launch because ");
if (temperature_is_low)
printf("the temperature is low");
if (temperature_is_low && is_raining)
printf(" and ");
if (is_raining)
printf("it's raining");
printf(".\n");
You could do something like:
#define avgTmpErrMsg "the temperature is below 42 degrees"
#define lowTmpErrMsg "the temperature has dropped below 32 degrees in the past day"
#define rainingErrMsg "it's raining"
short state = (avgTmp < 42) + ((lowTmp < 32)<<1) + ((raining)<<2); // store the state in one simple variable
short nErr = (avgTmp < 42) + (lowTmp < 32) + (raining); // number of error
switch(nErr){
case 0: // no error
printf("could launch\n");
break;
case 1: // one error
printf("The plane is not launching because %s\n", msg(state,1));
break;
case 2: // 2 errors
printf("The plane is not launching because:\n%s\n%s\n",msg(state,1),msg(state,2));
break;
case 3: // 3 errors
printf("The plane is not launching because:\n%s\n%s\n%s\n",msg(state,1),msg(state,2),msg(state,3));
break;
}
char* msg(short err,short n) {
/* print the nth error stored in err */
return ((err&1 && (!(--n)))? avgTmpErrMsg : ((err&2 && (!(--n)))? lowTmpErrMsg : rainingErrMsg));
}

Too few arguments in function to call [C program]

So, I have an assignment due tomorrow night for my online C programming class, and I am having some problems with my coding at the moment. I have brought the code to my teacher, but she doesn't seem to understand that she is being paid to teach me, not tell me that something is wrong with my code. I would appreciate if someone could take a look at the code and help me fix it. Code is located below. The location where I get my error is in main when calling the printtripSummary.
#include <stdio.h>
void welcomeMessage();
void askuserForInput();
void printtripSummary(float avgMiles, float minCost, float maxCost, float travelMiles);
int main()
{
/* Call the functions */
welcomeMessage();
askuserForInput();
printtripSummary();
printf("\nThank you, please drive safely and have a nice trip!\n");
return 0;
}
void welcomeMessage()
{
printf("Welcome to the Trip Planner!\n");
printf("So you are ready to take a trip? Let me help you plan for\n");
printf("your fuels costs and required stops to fill up your tank.\n");
printf("============================================================\n");
printf("Please provide answers to the prompts below and I will\n");
printf("display a summary for you when I have computed the results.\n");
printf("============================================================\n");
}
void askuserForInput()
{
float avgMiles, minCost, maxCost, travelMiles;
do{
printf("Please input your car's average miles per gallon (enter 0 to quit)>> ");
scanf_s("%f", &avgMiles);
if (avgMiles == 0)
break;
printf("Please tell me the range of fuel costs you expect to pay (per gallon>>)\n");
printf("The lowest per gallon cost of fuel is>> ");
scanf_s("%f", &minCost);
printf("The highest per gallon cost of fuel is>> ");
scanf_s("%f", &maxCost);
printf("Please tell me how many miles you plan to travel>> ");
scanf_s("%f", &travelMiles);
printtripSummary(avgMiles, minCost, maxCost, travelMiles);
} while (avgMiles != 0);
}
void printtripSummary(float avgMiles, float minCost, float maxCost, float travelMiles)
{
float avgGal, mingasPrice, maxgasPrice;
do{
avgGal = travelMiles / avgMiles;
mingasPrice = avgGal * minCost;
maxgasPrice = avgGal * maxCost;
printf("You will be required to purchase %.2f gallons of fuel.\n", avgGal);
printf("The price will range between %2f and $%.2f.\n", mingasPrice, maxgasPrice);
} while (avgMiles != 0);
}
Comment out the function call in main like this (Line 13):
//printtripSummary();
Because you call the function already in askuserForInput(); and this function get called in main
OR if you want to call the function also in main your have to pass the required arguments which are:
(float avgMiles, float minCost, float maxCost, float travelMiles)
Also you have a endless loop in the function printtripSummary(); Because you have a do...while loop which checks if avgMiles != 0, but since your not changing the value of avgMiles in this loop it's endless!
On line 13 you're calling the printtripSummary function without passing any arguments to it. You have to provide the 4 arguments the function definition specifies (avgMiles, minCost, maxCost, travelMiles).

remove trailing zeros from output

So my program works and compiles it does what I ask.
But my program's output has these trailing zeros that I would like to eliminate.
It's not like it bothers me but I definitely would like to have it cleaned up a little.
If anyone could give me a little insight on how to eliminate the trailing zeros your help,
would be greatly appreciated.
#include "stdafx.h"
#include "stdio.h"
#define BPR 10 // Basic Pay Rate is $10.00/hr.
#define OTPR 15 // Over Time is time and a half.
#define OT 40 // Overtime is after 40 hours.
#define RATE1 .15 // Tax Rate 15%.
#define RATE2 .20 // Tax Rate 20%.
#define RATE3 .25 // Tax Rate 25%.
#define LIMIT1 300.00 // The first 300.00.
#define LIMIT2 200.00 // 200 after the first 300.
int main(void)
{
int hours;
double tax;
double gross;
double taxes1=0,taxes2=0,taxes3=0;
double net;
double hold1=0,hold2=0,hold3=0;
printf("Please enter hours worked: ");
scanf_s("%i", &hours);
if(hours < OT)
gross=hours*BPR;
else
gross=((hours-OT)*OTPR+(OT*BPR));
if(gross > LIMIT2 && gross < LIMIT1)
taxes1=gross*RATE2, hold1=gross-taxes1;
if(gross > LIMIT1)
taxes2=gross*RATE1, hold2=gross-taxes2;
if(gross < LIMIT2)
taxes3=gross*RATE3, hold3=gross-taxes3;
if(gross > 0)
{
net=(hold1+hold2+hold3);
tax=(taxes1+taxes2+taxes3);
}
printf("Your Net Pay is %f\n", net);
printf("Your Gross Pay was %f\n", gross);
printf("Your Taxes paid are %f\n", tax);
return 0;
}
if 65 was put in for the hours variable the output would read:
Your Net pay is 828.750000
Your Gross Pay was 975.000000
Your Taxes paid are 146.250000
as you can see there are a lot of zeros I would love to have disappear please help ?
Use %.2f as the output format.
You can specify how many positions you want to display after the decimal point using . followed by the number of positions between % and f like so: printf("Your Net Pay is %.2f\n", net);. There are other formatting options that can be used with format specifiers and you can read more on them in the man pages by doing man printf since printf is not just a C function.

Resources