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?)
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 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 4 years ago.
Improve this question
I need to convert defined constants to their integer values so I came up with this macro (STR_TO_CONST) for doing so...
#define STRFY_VAL(s) #s
#define STRFY_KEY(s) STRFY_VAL(s)
#define STR_TO_CONST(s) atoi(STRFY_KEY(s))
It works, but I'm wondering if there are any potential problems with it as I've never encountered this macro before despite having searched considerably for something like it.
The reason you never encountered this is that it's utterly pointless, but let's explain by example. Say you have the following:
#define FINALANSWER 42
// ...
int x = 2 * STR_TO_CONST(FINALANSWER);
now, this is semantically no different from:
int x = 2 * FINALANSWER;
That's because preprocessor macros are ultimately just textual replacement happening before you actually compile. Therefore, FINALANSWER is just as good as an integer constant as 42 is.
Your "solution" to a non-existing problem just adds overhead in that it adds a new string constant to your code and an unnecessary function call as well.
I'm wondering if there are any potential problems with it (?)
Yes. Using atoi() to initialize a global results in something like "error: initializer element is not constant"
int x = STR_TO_CONST(123); // error
int y = 123; // no error
int main(void) {
return x + y;
}
Hide warnings. Only 1 line generated a useful warning
"warning: overflow in implicit constant conversion [-Woverflow]"
int main(void) {
int a = STR_TO_CONST(123456789012345); // no warning
int b = 123456789012345; // warning
return a + b;
}
Range issue. With 32-bit int, the below will likely exceed atoi() range resulting in undefined behavior with no warning.
int main(void) {
long long z = STR_TO_CONST(123456789012345);
return !z;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am rounding off some values and then printing them. When I use %f option, they are printed correctly, but using the %d or %i option (even after casting the rounded values to int) is giving a weird output, and I am not able to figure the why of it out.
Any help is much appreciated!
When I use %f:
i = 0;
while(i < n_shapes)
{
ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
printf("%f,%f,%f,%f\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
i++;
}
Output:
115.000000,94.000000,115.000000,101.000000
116.000000,51.000000,117.000000,58.000000
116.000000,60.000000,117.000000,67.000000
116.000000,69.000000,117.000000,75.000000
116.000000,77.000000,117.000000,84.000000
116.000000,86.000000,117.000000,93.000000
116.000000,94.000000,117.000000,101.000000
Now, with %d (or %i):
i = 0;
while(i < n_shapes)
{
ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
printf("%d,%d,%d,%d\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
i++;
}
Output:
1079590912,0,6,-1
1078788096,0,5,-1
1079033856,0,6,-1
1079164928,0,6,-1
1079312384,0,6,-1
1079459840,0,6,-1
1079590912,0,6,-1
Thank you!
Edit: Yes, I realize that using (int) in the printf gives me the right output. I was curious about the values I got when I didn't do so. What does my output when I use %d without casting inside the printf mean?
This is undefined behavior. You need to use the correct type specifier.
printf cannot verify that the types of parameters that you pass to it for printing match their corresponding format specifiers. The compiler performs type-specific conversions before passing these parameters, so printf expects that for each %f if would find a double (float gets converted to double as well) and for each %d it would find an int. Your code passes a double-converted value for that %d specifier, which causes undefined behavior.
Note that casting a float or a double expression to int before assigning to a float or double variable does not change the representation of the number. All it does is truncating the fractional part. The representation remains the same. In other words, if you do
double x = 12.345;
double y = (int)x;
it is the same as
double x = 12.345;
double y = (double)((int)x);
because in this case the compiler knows the type of variable y, and inserts the missing cast for you.
The first thing to learn about gcc is that you need to turn warnings on explicitly and make them errors using -Wall -Wextra -Werror. These are going to warn you about many useful things if you do not do them exactly right.
Including the format string and wrong argument types as you have here.
I guess the reason why these warning options are not enabled by default is that good-old-perfectly-working-K&R-code would now produce warnings and upset some venerable hackers.
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.