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
I am working on a program that will convert from dollars to cents. I take in user input as a float using a predefined function then i try to multiply this float by 100 but it gives me an incorrect value. Heres the code:
printf("Change in dollars: ");
change= GetFloat();
cents= round(change*100);
printf("Cents is %f",cents);
This is a logical error because the program runs fine but there is something wrong with the mathematics for example if i enter 1.50 when prompted, the return i get is 1004 which is clearly wrong. What i want to happen is 150 to be outputted.
This is most likely because you have some locale where the decimal separator is , instead of ., and since you are very likely not checking the return value of scanf() "which is what most books do and almost every tutorial", then the variable is not being initialized and what you are printing is a consequence of the layout of your program instead of a value inputed by a user.
To verify what I say, I suggest compiling the same program without modification but with different compilation flags.
What you must do is ensure that the input is correct, try this
float GetFloat(int *ok)
{
float value = 0;
if (scanf("%f", &value) != 1)
*ok = 0;
else
*ok = 1;
return value;
}
which you would call like this
int result = 0;
float change = GetFloat(&result);
if (result == 0)
return -1;
float cents = round(change * 100);
printf("Cents is %f",cents);
If the decimal separator is an issue, the above program will not output anything, because scanf() will return 0, and hence ok will be 0 after you call the function.
One important consequence of ignoring the return value of non-void functions is that if the value was not initialized like in this case with scanf(), and you don't know that because you didn't check the return value, then undefined behavior will happen, meaning that your program will contain bugs that are very difficult to find and hence very hard to fix.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The following C code takes so long to compile and execute.
#include <stdio.h>
int main()
{
int max;
printf("Enter a value for max: ");
scanf("%d", &max);
for (int i=0; i<max; i++)
{
printf("%d\t", i);
}
return 0;
}
But, If I initialize the max variable with some number like
int max = 0;
The Compilation and execution is almost instantaneous. Can someone explain why?
Edit:
When I printed the value of the variable max before my input, it showed 2203648 (some garbage value). Instead of "int max = 0", if i assign
int max = 2203648;
the compilation and execution takes the same long time. But, as mentioned earlier, if i assign max say
int max = 200;
the compilation and execution is instantaneous. Does it have to do anything with the pre-assigned garbage value?
Also, this problem occurs only in windows computers, I tested with ubuntu, and the compilation and execution is instantaneous in both version of the code.
In Windows 10:
compilation and execution, as of "Enter a value for max: " appears on screen:
without variable initialization = around 8 seconds
with variable initialization = instantaneous
compiler - gcc
The scanf is failing. Check the return value.
i.e.
if (scanf("%d", &max) != 1) {
fprintf(stderr, "Unable to read max");
exit(1);
}
max is probably some large value hence the large amount of time
EDIT
The delay to see the prompt is that the printf is in a buffer and will not be displayed until the loop completes
I think variable initialization of max=0 doesn't make that great deal of a difference, but god knows why in ypur case its taking 8seconds. I think you should reinstall your GCC Compiler set your path variables correctly once more, and try the above code on a different IDE.
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 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).
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
Here is all the code I have in Visual Studio:
#include <stdio.h>
int main (void) {
int input;
puts("There are 10 seats available on the next flight");
puts("Where would you like to reserve a seat?");
puts("Please type 1 for First Class");
puts("Please type 2 for Economy");
scanf("%d", &input);
if (input == 1) {
printf("You Typed %d\n", &input);
}
if (input == 2) {
printf("You Typed %d\n", &input);
}
}
But when I run the program I get output that says:
There are 10 seats available on the next flight
Where would you like to reserve a seat?
Please type 1 for First Class
Please type 2 for Economy
1
You Typed 6159588
Press any key to continue . . .
I get a totally random number every time. Because of this I can't seem to get anything I write after the input to work. Why is this happening?
What you get printed out is the address of the variable input, not its value! This is because printf accepts its arguments by value - simply because they can be passed like that. What you need thus is
printf("%d", input); // without the ampersand!
scanf - in contrast - is fundamentally different. It is going to place a value into a variable you provide to it - and therefore needs a pointer.
Simple example:
int n = 7;
void myPrintf(int v)
{
++v;
}
void myScanf(int* v)
{
++*v;
}
int main(int argc, char* argv[])
{
myPrintf(n); // n passed by value, cannot be modified
// (but printf does not intend to, either!)
myScanf(&n); // n will be incremented!
// (scanf does modify, thus needs a pointer)
return 0;
}
Back to the roots, though: There is still a fundamental problem: You are passing a pointer, but evaluate it as an int. If sizes of both differ - which is the case on modern 64-bit hardware - you are in trouble. The value then is read from the stack with different size and part of your address actually gets discarded (pointer addresses require "%p" format specifier, assuring that the apprpriate number of bytes is read from stack - in case of modern systems 8 vs. 4 for int).
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
I was suppose to get distance and speed from user and to return the time.
Here's the code I did:
int main()
{
int distance, speed;
scanf("%d,%d", &distance, &speed);
printf("%d\n", distance / speed);
printf("%d hours and %d minutes", (distance/speed), (distance / speed)%60);
}
For the values:
10 10
I receive 0 as output.
The problem here is, you did not check the return value of scanf() to ensure it's success.
By property, the format string supplied with scanf() should exactly match with the input, otherwise, due to matching failure, the receiving arguments won't get the expected value.
With a format string like
scanf("%d,%d", &distance, &speed);
an input
10 10
is not proper, you need to enter like
10,10
to match the , in the format string.
Otherwise, you can remove the , from the format string also, and provide the input in space-delimited format.
[Edit]:
To enforce a floating point division, please chnage your statement to
printf("%f\n", ( (float)distance / speed ) );
printf("%f hours and %d minutes", ( (float)distance / speed ), (distance / speed)%60);
You need to enter 10,10 because that's what you require with your scanf().
Then of course your calculation are incorrect. You'll get 1 and 1 for both hours and minutes.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been playing around with the code below just trying to get it to compile with the Borland compiler (It's the compiler I have to use - I'd much prefer to use GCC on Linux but here we are) but having no luck - can anyone see any obvious flaws?
Code
#include<stdio.h>
#define SIZE 10
float money() {
float wages[SIZE], rise, total; // where i is initaliser
float percent = 0.2;
int i = 0, j;
for(i = 0; i<SIZE; i++) {
wages[i] = j; // Initializing each element seperately
}
printf("Please enter the wages for each staff member\n");
scanf("%d*%c", &wages[i]);
rise = wages[i] * percent;
total = rise + wages[i];
printf("The new wage is $%f and appears in the %d array slot\n", total, j);
return(0);
}
int main() {
money();
return(0);
}
Compiler output
Warning W8004 payrise.c 8: 'i' is assigned a value that is never used in function money
Warning W8065 payrise.c 23: Call to function 'money' with no prototype in function main
These are both warnings; in this case the code referred to by the warnings is correct but it could have its style improved. You should be able to run the program even though it showed warnings; since there were no errors. (BTW you should have help files that came with the compiler; these will tell you what the warnings mean if you find the warning text unclear).
The first warning is because you have:
int i = 0;
for (i = 0;
i.e. the first setting of = 0 is redundant because you immediately set it to 0 again.
The second warning is because you did not provide a prototype for money. You should declare the function as:
float money(void)
This makes it be a prototype, which has the effect that the compiler will flag an error if you later try to pass an argument to the function.
However, your code has other bugs which the compiler did not diagnose (or if it did, you didn't let us know).
Firstly you use j without initializing it. You should give it a value before using it.
Secondly, scanf("%d*%c", &wages[i]); is wrong. The format specifier for float is "%f", not "%d*%c". Also , i is out of range at this point (did you mean to have this code inside the loop?)