if-else code for total price won't compile - c

what is wrong with this im to make c code for total price with one of three ram options.et ramchoices=1or2or3 /this is where I know my problem lies but don't know how to fix it. the compiler needs a one to one relationship. how do I break this up and still show that ramchoice depends on what I pick and those choices affect price./
int main(void) {
/*declare variables*/
float baseprice;
float total;
float ramchoice;
baseprice=1029.48;
/*ramchoice can be 1 or 2 or 3*/
ramchoice=1||ramchoice=2||ramchoice=3;
total=baseprice+ramchoice;
/*initiate variable*/
scanf("%f",&ramchoice);
if("%f" (ramchoice==1))
{
total=baseprice+179.99;
}
else if("%f" ramchoice==2)
{
total=baseprice+94.99;
}
else if("%f" ramchoice==3)
{
total=baseprice+69.99;
}
printf("total is %f",total);
return 0;
}

There are several lines that are unlike any C code I've ever seen before.
Are you completely making up your own syntax and meaning?
Have you read any instructions/tutorials on C?
ramchoice=1||ramchoice=2||ramchoice=3;
Whatever you think this line does, it sets variable ramchoice to have value 1, then it stops.
if("%f" (ramchoice==1))
if does NOT take a string like "%f". if expects a boolean expression.
You're close to a boolean with ramchoice==1, but the "%f" at the start is so very wrong.
Seriously, you cannot make up rules to a language and pray that it works.
Here is my re-write that pretty much fixes your issues:
int main(void)
{
/*declare variables*/
float baseprice = 1029.48;
float total;
int ramchoice;
printf("Please enter a ram selection: 1, 2, or 3\n");
scanf("%d",&ramchoice);
switch(ramchoice)
{
case 1: total=baseprice+179.99; break;
case 2: total=baseprice+94.99; break;
case 3: total=baseprice+69.99; break;
default: printf("That was not a valid choice\n");
}
printf("total is %f",total);
return 0;
}

There's somethings in your code that make no sence (are not correct in C):
ramchoice=1||ramchoice=2||ramchoice=3; total=baseprice+ramchoice;
"%f" (ramchoice==1)
The first I don't understand why you are using it.
The second one gives me the idea that your not understanding how scanf works.
Also, you are declaring ramchoice as a float, but you are comparing it to another value (1, 2 or 3). Due to the representation of float values, this may not work. I mean, if you have float x = 1; and then do x == 1, it may return false. To fix this you can just change it to an int (in this case, in others you can use an error margin).
Here's a fix of your code:
int main(void) {
/*declare variables*/
float baseprice;
float total;
int ramchoice;
baseprice=1029.48;
/*initiate variable*/
scanf("%i",&ramchoice);
if(ramchoice==1)
{
total=baseprice+179.99;
}
else if(ramchoice==2)
{
total=baseprice+94.99;
}
else if(ramchoice==3)
{
total=baseprice+69.99;
}
printf("total is %f",total);
return 0;
}

Get rid of the "%f" in the if statements
Comment those 2 lines:
ramchoice=1||ramchoice=2||ramchoice=3;
total=baseprice+ramchoice;
and code should compile.

Related

Keep getting the same answer when writing a recursive function

Note: I'm fairly new to C programming so I don't know everything just yet.
So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.
This is what my code is:
#include <stdio.h>
int count_digits(int num)
{
static int count=0;
if(num>0)
{
count++;
count_digits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
printf("Enter any number:");
scanf("%d",&number);
count=count_digits(number);
printf("\nTotal digits in [%d] are: %d\n",number,count);
return 0;
}
Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:
return count_digits(num/10);
there are a few things to consider:
What happens if you call your function count_digit() more than one time in the program?
What if you enter 0, 10, 100 as number?
Perhaps you should rethink using a static variable here.
Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

i can only call a function once to compare 2 numbers using pointers

i have to compare 2 numbers using pointers but i can only call my function one time to get the number then i have to find the largest number from the 2. then I have to display which one was largest.I am having a hard time beacause I dont know where I went Wrong because the second number it always says is larger when I enter the larger one first. Can someone help? Here is what I tried.
#include <stdio.h>
void getnumbers(float*,float*);
float findlargest(float*,float*);
void displaylargest(float);
int main ()
{
float num;
float num2;
float largest;
getnumbers(&num,&num2);
largest=findlargest(&num,&num2);
displaylargest(largest);
return 0;
}
void getnumbers(float*num,float*num2)
{
printf("Enter a number\n");
scanf("%f",num);
printf("Enter a number\n");
scanf("%f",num2);
}
float findlargest(float*numptr,float*num2ptr)
{
if (*numptr>*num2ptr) {
return *numptr;
}
else {
return *num2ptr;
}
}
void displaylargest(float largest)
{
printf("\nthe largest is %f ",largest);
}
Lets start with getNumbers():
To get a function to return more than one value, you can pass parameters by reference. This post has a good explanation of passing parameters by reference.
When we pass-by-value we are passing a copy of the variable to a function. When we pass-by-reference we are passing an alias of the variable to a function.
Where the alias is a pointer to the memory location of num or num2 declared in main() (see function below). This allows you to change their value inside the function the variables were passed to.
void getnumbers(float *num, float *num2)//pass by ref to get two numbers
{
printf("Enter a number\n");
scanf("%f",num);//"%2f" is not something you would do
printf("Enter a number\n");
scanf("%f",num2);//assign to num2, not num
}
Now findLargest() really does not need to be taking pointers as parameters, but it can if the assignment requires. You would only do that if you intend to change their value. If you need to only use the value, you just pass by value:
//much more concise and does the exact same thing!
//Normally wouldn't use pointers here, but it is a requirement for the assignment
float findlargest(float *num, float *num2)
{
return *num > *num2 ? *num : *num2;
}
Now your main becomes:
int main ()
{
float num = 0;//always a good idea to initialize variables!
float num2 = 0;
float largest = 0;
getnumbers(&num, &num2);//pass by reference
largest = findlargest(&num, &num2);//pass by value
displaylargest(largest);
return 0;
}
i believe it is because you are using the same variable to enter a number
i.e. num 2 doesn't have a value
void getNumbers(float *num1, float *num2){
printf("Enter a number\n");
scanf("%2f", num1);
printf("Enter a number\n");
scanf("%2f", num2);
}
this passes the num1 and num2 variable by "call by reference" and allows you to directly modify the value stored in the pointer num1 and num2, so you don't have to return any value too.
then when you compare it should compare two values you enter in now.
You are never assigning num2 in main. Your getnumbers function asks the user for two numbers and only returns one of them. I don't know why you have to use pointers for your getlargest function -- that makes no sense -- but if those are your requirements, then okay.
To fix your problems, rewrite getnumbers to take in two pointers to float where you will then pass to scanf.
Your main () function inside the num2 is not assigned, because the initial num2 is 0, so you get the result is always num2 the smallest。
Your getnumbers () also has an error, it can only return the last keyboard input value。
bie jiao yin yu.
your function "getnumbers" only return one value,num2 Uninitialized.
There are 2 solution:
(1)add
num2 = getnumbers();
and delete
printf("Enter a number\n");
scanf("%2f",&num);
(2)modify your function
getnumbers(&num, &num2);
void getnumbers(float *num1,float *num2) {
printf("Enter a number\n");
scanf("%f",num1);
printf("Enter a number\n");
scanf("%f",num2);
}

Error when using array elements in conditional statements in C

I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.
From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.
Here is the code:
#include <stdio.h>
int power (int x, int y); //prototype
int main(void)
{
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);
//initialize array
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
//verify binary input
for (test=4; test>=0; test--){
if ((bin[n]!=0)&&(bin[n]!=1)){
printf("Error. Number entered is not binary.\n");
return 0; }
//convert to decimal
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;
}
//function definition
int power(int x, int y)
{
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;
}
Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.
Update: If the if statement is moved to the while loop before. This should still work right?
Update2: Never mind, I noticed my mistake. Moving the if statement to the while repetition before does work given the solution supplied by sps and Kunal Tyagi.
After this
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
n is set as -1 so when you try to convert to decimal the statement bin[n] is actually bin[-1] so it returns you error.
One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1))
printf("Error, numbered entered was not binary.\n");
// Issue here, you are returning outside if
return 0; } //exit program
You can change that to:
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1)) {
printf("Error, numbered entered was not binary.\n");
// Return inside the if
return 0; // exit program
}
}
There is one more issue. Before you convert your number to decimal, you need to set n = 0;
//convert to decimal
n = 0; /* need to set n to zero, because by now
n will be -1.
And initially when n is -1, accessing
bin[-1] will result in undefined behavior
*/
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
This looks like a homework, but your issue is in the brackets. More specifically line 23. That line is not part of the logical if statement despite the indentation (since that doesn't matter in C).
No matter what, the program will exit on test=4 after checking the condition.
Solution:
if ((bin[test]!=0)&&(bin[test]!=1)) { // << this brace
printf("Error, number entered was not binary.\n");
return 0; } } //exit program // notice 2 braces here

Programming C calling function area of circle and rectangle

#include <stdio.h>
#define PI 3.14159
int Circle (int);
int Rectangle (int, int);
int main()
{
int a;
int b;
int c;
int d;
int area;
int AreaOfCircle;
int AreaOfRectangle;
int area1;
printf("Program to calculate area\n");
printf("1 - Circle\n");
printf("2 - Rectangle\n");
printf("\n");
printf("What option = \n");
scanf("%d", &a);
if(a=1)
{
area=Circle(b);
printf("Area= %d\n", area);
}
else if(a=2)
{
area1=Rectangle(c,d);
printf("Area= %d\n", area1);
}
return 0;
}
int Circle (int b)
{
int area;
printf("radius= \n");
scanf("%d", &b);
area=PI*b*b;
return area;
}
int Rectangle(int c, int d)
{
int area1;
printf("length= \n");
scanf("%d",&c);
printf("width= \n");
scanf("%d",&d);
area1=c*d;
return area1;
}
//I want to ask if my coding is ok .. but as I run it the output only ask for radius which is the calling function for circle .. but if i want to call rectangle the output also shows calculation for circle .. can someone help me to spot the mistake .. by the way this is my first coding about calling function and I just started learning coding c last month .. T-T
With C you use == to evaluate (e.g. if (x == 1)). "=" is assignment, so you'll always hit the first block.
Also, you're accepting parameters which you're then modifying, which is not good practice. Consider declaring your variables at usage time also, the "everything at the top of the block" paradigm is very dated.
This question is not about functional programming, this is an example of imperative programming.
Also, your input being poured directly into an integer is not bounds checked, consider a switch/case so you can add a default of "invalid input" and extend to different shapes in the future.
Yes bro just make if(a==1) and else if(a==1).
You've used the assignment = operator instead of the comparison == operator.
A statement like
if(a=1)
will assign a value of 1 to a and check then check for the non-zero value of a [which always evaluates to TRUE].
Instead, what you want is
if (a == 1)
which evaluates to TRUE if a contains 1. Same for other comparison(s) also.
Note: In your int Circle (int b) case you're storing the result to an int, which will truncate the result of a double/float multiplication. To get the exact value, make the area as float or double and use %f/ %lf format specifier.
Next, as per the logical part, you don't need to pass b, c, d as parameters to the called functions. Simply a local variable in the functions would do the job.

Multiplying numbers in C

I have written the following code to multiply two numbers and I see the result to be incorrect. I assume the data type is not holding the value right. But the answer its printing is incorrect.
#include<stdio.h>
main()
{
long int val1,val2;
val1=val2=1235;
char c = 'y';
switch(c)
{
case 'y' : printf("%20d",val1*val2);
break;
default: printf("invalid");
break;
}
return 0;
}
OUTPUT :
17897 //which is not the right answer
//it should actually be 1525225
Data type is holding the right value but you are using the wrong specifier. You should use %ld with long int.
printf("%20ld",val1*val2);
I double checked and it worked.

Resources