Cannot figure out why my code is not working [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've been trying to figure out what is wrong with my code for days; I can't seem to find it. If statements confuse me quite a bit, so I'm thinking I messed those up, but still not sure. All I know is that I'm super stumped and would love all of the help I can get.
#include <stdio.h>
// function main begins program execution
int main(void)
{
int numberOfDays = 0;
float numberOfMiles = 0;
float milesCharge = 0;
float milesTotal = 0;
float total = 0;
float subtotal = 0;
float tax = 0;
do {
printf("%s", "How many days was car rented?\t");
scanf("%d", &numberOfDays);
} while (numberOfDays < 1 );
do {
printf("%s", "How many miles were driven?\t");
scanf("%d", &numberOfMiles);
} while (numberOfMiles > 1);
if (numberOfMiles > 1 || numberOfMiles < 200) {
milesTotal = numberOfMiles * .40;
} else {
milesTotal = numberOfMiles * .35;
}
subtotal = milesTotal + numberOfDays * 15;
tax = subtotal * .06;
total = tax + subtotal;
printf("\nSubtotal:\t\t\t$%.2f\n", subtotal);
printf("Tax Amount:\t\t\t$%.2f\n", tax);
printf("Total:\t\t\t\t$%.2f\n", total);
printf("\n");
}

If numberOfMiles should be of type float you have to exchange the following line
scanf("%d", &numberOfMiles);
by
scanf("%f", &numberOfMiles);
or you can set the type to int.
--
If you want to avoid an endless loop, exchange
} while (numberOfMiles > 1);
by
} while (numberOfMiles < 1);
Btw. why not allow distances that are shorter than a mile?
e.g. by
} while (numberOfMiles < 0);
For more specific answers, you have to be more precise.

Compiling your program with gcc gives the following warning:
t.c: In function ‘main’:
t.c:21:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%d", &numberOfMiles);
^
The problem is, that scanf() will store the number entered at the location of numberOfMiles using a binary format used for int variables, but numberOfMiles is a float variable. The integer bit pattern interpreted as float will probably have a very different meaning, or even can be an illegal float value.
Changing the type of numberOfMiles from float to int fixes this problem.
You also should change the second while condition to while (numberOfMiles < 1).
I hope, this helps.
73, Mario

Related

How to make a prompt in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
New programmer here, I have a few lines of code that I've finally managed to get to function but I'm running into a bit of a design issue. The code itself, at least to me, function as intended but I don't know how to get my terminal to display "Insert number here". This is how to code currently looks.
#include "cs50.h"
#include <stdio.h>
int main(void)
{
int n;
do
{
n = GetInt();
printf("Your number is!"/n);
}
while (n<1)
{
return n;
}
}
I'm looking for a way to get the same outcome as n = get_int ("Insert number: "); but that method brings up errors such as:
prompt.c:10:7: warning: implicit declaration of function 'get_int' is
invalid in C99 [-Wimplicit-function-declaration]
{ n = get_int("Insert number here %i\n", n);
or if I'm using n = GetInt("Insert number: "); I get this error message.
prompt.c:10:14: error: too many arguments to function call, expected 0,
have 2
{ n = GetInt("Insert number here %i\n", n);
~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/cs50.h:87:1: note: 'GetInt' declared here
int GetInt(void);
^
1 error generated.
Is there a way to get this to function so my terminal can prompt me with "Insert number here: ". Thank you and cheers!
If you want to print "Insert Number here:", you may use the prinf function.
#include <stdio.h>
int main()
{
int testInteger;
printf("Insert Number here: ");
scanf("%d", &testInteger);
printf("Your Number is %d",testInteger);
return 0;
}

My code is not woriking. am I doing it wrong? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I just have studied programming and english. I'm a newbie.
My code is supposed to show a sum of 1 to entered number.
(ex : if you enter 5, answer is 15 and if you enter 10, answer is 55)
Bu this code is not working. I have tried many times to fix it, but i don't know why this code is not working.
#include <stdio.h>
int main(void){
int i = 0;
int sum;
int j;
scanf("%d\n", sum);
for(j = 1; j <= sum; j++){
i = i + j;}
printf("%d\n", i);
return 0;
}
The problem with your code is a simple one, and a decent compiler will warn you about it:
testprog.c: In function ‘main’:
testprog.c:9:11: warning: format ‘%d’ expects argument of type ‘int *’,
but argument 2 has type ‘int’ [-Wformat=]
scanf("%d\n", sum);
^
The scanf function requires the address of items you want populated since it needs to change them. Passing the actual item (since C is pass-by-value) to a function could only ever change the copy rather than the original.
You can see the correct way to do it in the standard:
d: Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer.
As an aside, I've fixed that issue and added some more improvements, such as:
less confusing variable names (at no stage is your sum variable a sum of anything);
better (more logical) layout of code;
better scoping of temporary variables like i.
prompting the user for input so that they know what they're supposed to enter; and
checking for valid input by checking return value of scanf.
The code is:
#include <stdio.h>
int main(void){
int maxNum;
int sum = 0;
printf("Enter number to sum up to: ");
if (scanf("%d", &maxNum) != 1) {
fprintf(stderr, "Problem getting input\n");
return 1;
}
for (int i = 1; i <= maxNum; ++i) {
sum += i;
}
printf("Sum is %d\n", sum);
return 0;
}
Try this :
#include <stdio.h>
int main(void){
int i = 0;
int sum;
int j;
scanf("%d", &sum);
for(j = 1; j <= sum; j++){
i = i + j;}
printf("%d\n", i);
return 0;
}
Your mistake is just wrote scanf("%d\n", sum) instead of scanf("%d", &sum);
c language supports a type of call by value what transfers data copied.
So, you need to give the memory address that scanf function can write user's input to the sum variable memory.
scanf("%d", &sum)

function returns not expected value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i have a function that counts arithmetic mean of even numbers in an array.
int func(int *x, int length)
{
float even_sum = 0;
int even_num;
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++;
}
}
result = even_sum/even_num;
return result;
}
giving an array 1 2 2 1 i expect to receive 2 as mean, but i keep getting 0 as result. Where is a mistake in my code?
int func(int *x, int length)
{
float even_sum = 0;
int even_num; // <-- uninitialized, could be anything!
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++; // <-- adding 1 to anything yields undefined behavior
}
}
result = even_sum/even_num; // <-- even more undefined behavior
return result;
}
You initialized some, but not all of your variables. It's best to get in the habit of setting your variables to sensible starting values, just as you do here with float even_sum = 0;
Initialize even_num=0
If you don't initialize variables, they can have garbage values.
In your case, even_num has a huge values, greater that even_sum causing your result to be 0.
#Pbd is correct. If you have the latest version of gcc installed and use the command line flags -Wall -Wextra -Wshadow when compiling, it will give you a warning for uninitialized values. 🤓
I think The only problem in your code is when you are passing int array into this function. Apart from that everything looks fine. I ran the code by initialling the 'x' array and it is working fine.

Unable to use variable value outside for loop in C program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am following a introductory C programming course and the first assignment is to find number of perfect squares in a given range.
I am trying to get the first perfect square root, but when I try to assign the first square root to a variable, i am unable to do so and it always shows 0.
This is the program that I have written:
#include<stdio.h>
void main()
{
float y= 0;
float k = 1.0;
float n;
int i=0;
int first_sqrt;
first_sqrt = 0;
printf("enter number: \n");
scanf("%f",&n);
// finding the first perfect square
for(y = 0; y<=10000; y++)
{
while((k*k - n)>0.0001 || (n - k*k)> 0.0001)
{
k = (k + n/k) / 2;
//printf("%f\n", k);
}
i = (int)k;
if(i*i == n)
{
printf("perfect squareroot: %d\n", i);
i = first_sqrt;
y = 10001;
//break;
}
else
{
printf("not perfect square: %f\n", n);
n = n+1;
}
}
printf("first perfect square root: %d\n", first_sqrt);
}
I am sorry for posting the whole program, but I have no idea where the problem might be. This is the first assignment of the first week so I don't have understanding of a lot functions in C yet and I can't use math function for this assignment.
Any help would be appreciated. Have been searching all day about this but couldn't understand much.
A basic direction towards the problem would be most appreciated. Thanks.
The expression i = first_sqrt; assigns first_sqrtto i and not i to first_sqrt. Change it to first_sqrt = i;. Apart from this you can remove the comment from //break;.
Reverse this line
i = first_sqrt;
to first_sqrt = i;
You mixed up an assignment. This:
i = first_sqrt;
Should be:
first_sqrt = i;

Program in C to sum each digit in an integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
int main(){
int x;
int sum;
printf("Enter a positive integer: ");
scanf("%d", &x);
do{
sum += (x%10);
x=(x/10);
if((x/10)==0){
sum += x;
}
}
while((x/10)!=0);
printf("%d",sum);
}
Hey, I'm trying to get this to add up each digit within the entered integer, but the code I'm using keeps returning the wrong output. Would someone please help me fix my equation/code, because I'm not sure why the output is incorrect.
in your code
int sum;
is not initialized. use something like
int sum = 0;
Note: local variables are not automatically initialized [to 0 or anything], without explicit initialization their contents will be garbage. Thereby, using sum += (x%10); will lead to read before-write scenario, producing wrong result.
Here is a small math problem:
Somebody gave you ten apples, then someone else gave you two more. How many apples do you have?
The right answer is that this question is impossible to answer, because nobody told you how many apples you had at the beginning.
Your program suffers from the same problem: you failed to initialize sum before starting to add to it, so it has initial "garbage" value.
Changing the declaration to
int sum = 0;
will fix the problem.
Initialize your variable sum -
int sum = 0;
If you don't initialize your variable in C and some other language then the a garbage/random value is assigned to it when it is used in expression for the first time.
Late Answer
Since you've already found the problem with your code, I would like to provide a more concise alternative:
int x;
int sum = 0
int digit;
printf("Enter a positive integer: ");
scanf("%d", &x);
while (x > 0) {
digit = x % 10;
sum += digit;
x /= 10;
}
printf("%d", sum);
x % 10 extracts the last digit of the number, and then x /= 10 truncates the integer by removing the last digit.

Resources