For years, I don't do anything in C and now I can't do simple things, I was accustomed to cin and cout and now Java. I was trying to make a simple program to calculate the average X amount of exams notes. The output are "random numbers" and checking to interrupt the program occurs before entering a note. Why is that?
#include <stdio.h>
int main(void) {
int numeroDeNotas;
float nota = 0.0;
float notaAuxiliar = 0.0;
char continuar;
int media;
do{
printf("Enter the exam grade\n");
scanf("%f", ¬aAuxiliar);
nota += (int) notaAuxiliar;
numeroDeNotas++;
printf("Do you want to continue? Enter n if you want to stop\n");
scanf("%c", &continuar);
}while(continuar != 'n');
printf("%d\n\n", nota);
printf("%d\n\n", numeroDeNotas);
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
return 0;
}
nota is a float, but you are using %d format code to print it. %d expects an int; you need %f to print floating point numbers.
C's standard I/O formatting is definitely not typesafe. When you provide a format code, you have to make sure the corresponding argument has the right type. However, if you had compiled with the -Wall option (at least, with gcc or clang), the compiler would have warned you.
Also, scanf("%c", &continuar); reads a single character without skipping whitespace, which will be the character immediately following the number read by scanf("%f", ¬aAuxiliar);. That character is most likely a newline. You need to skip whitespace before reading the y or n, so you could use:
scanf(" %c", &continuar);
numeroDeNotas was declared with a variable type - float. So you can't use %d later in your code when writing a printf statement.
numeroDeNotas
variable is declared but no where initialized. and you are incrementing in do while loop.
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
and you are using garbage value to calculate media which is undefined output. initialize numeroDeNotas to zero.
Related
I am attempting to build a form/gpa calculator for class, but when entering the amount of classes using scanf, the output is 6,487,576 regardless of what I enter.
int main()
{
int opt;
int c;
printf("*******************************\n");
printf("** Fanshawe Grade Calculator **\n");
printf("*******************************\n");
printf("Please Choose an Option:\n");
printf("[1] Enter Your Marks\n");
printf("[2] Quit\n");
scanf("%d", &opt);
switch(opt) {
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", &c);
/*int i;
for(i=1;i=c;i++) {
printf("Enter Your Mark for Class #%i\n", &i);
}*/
break;
case 2 :
printf("GoodBye!");
exit(0);
break;
}
return 0;
}
Help please!
When you use %i with scanf(), it can allow you to input hexadecimal and octal numbers as well (this isn't an issue as explained here).
However, you shouldn't use & while using printf() as it'll display the memory location of the variable instead of the value stored in it.
Try this:
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%d", &c);
printf("You Have Entered %d Classes!\n", c);
break;
printf("You Have Entered %i Classes!\n", &c) outputs the address of the variable c (&c takes the address), i.e. it outputs the number of the memory cell. Since you want to pass the value of the variable you should not use the operator of taking address of a variable &.
printf("You Have Entered %i Classes!\n", c);
There are two problems here. First, you need to include the following headers:
#include <stdio.h> // declares functions like printf and scanf
#include <stdlib.h> // declares functions like exit
If you don't include these headers, then the compiler does not know how to execute them or their exact formats. When you attempt to compile, the warnings will not be helpful. There are a few good websites for this; just search something like "c exit()" in Google and it will tell you which headers you need in the future. When I compiled this code, I used gcc main.c -Wall which forces all warnings to be displayed.
Secondly, you use the address of c in both cases. When you go to print the value of c, you are actually printing the address of c, not the value. scanf() takes the address(es) of the variables to store values in, but printf() takes the variables themselves. The code should look more like this:
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", c);
It is also always a good idea to initialize your variables. This way, you know when something is assigned improperly, or not assigned at all. I forgot to assign my variables for a while, and when compiled on another machine, it didn't work. This is because different machines will initialize variables differently. Just change the code to the following:
int opt = 0;
int c = 0;
I was trying c code to add but my program doesn't execute, codeblocks unfortunately closes. What is the error?
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,(a+b));
}
I want to put the result of addition directly in printf statement with float inputs but I am not getting it working.
I also tried putting the result in variable a but it didn't work either.
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
}
where am I going wrong?
The problem is in the following statement
printf("%30sAddition Of Numbers\n");
here, the format string supplied to the printf() conatins %30s (or, %s, in general) which is a format specifier (conversion specifier), and you did not supply any argument to it. It invokes undefined behavior.
To quote C11 standard, chapter §7.21.6.1
[...] If there are insufficient arguments for the format, the behavior is
undefined. [...]
You can also check the man page to find out more about the format specifiers.
EDIT:
As discussed in the below comments, if you want some spaces to appear before the output, change
printf("\t\tAddition Of Numbers\n");
That said,
void main() should be int main (void), at least, to conform to the standards.
You should always check the return value of scanf() to ensure the successful scanning.
The "%30sAddition Of Numbers\n" issue in your post has been addressed by two good answers (at the time of this post). But you asked a question in comments that may not have been answered completely:
works with %30s when i use all integer numbers and not float! how do i make it work with floats.
A generic answer to that question:
The format specifier you use in scanf(): "%f",&a could result in undesirable results if scanning in unexpected newlines, spaces or other white space. This can be addressed by modifying the format specifier string to suppress these characters. Here is a suggestion:
char* fmt = "%[^\n]%*c";//This generic format specifier, can be used for both integer
//and floating point inputs when used in conjuction
//with strtod() or strtol() (see below)
scanf(fmt, input);
Explanation of "%[^\n]%*c".
When a user is asked to enter a generic number, it might be a float or an integer. You can accommodate that by creating methods for both, and being specific about what kind of value you would like to process:
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Called like this:
int main(void)
{
long integer_var = get_int();
float float_var = get_float();
float sum = (float)integer_var + float_var;
return 0;
}
Try adding getch(); function at the bottom before closing curly brackets,
like this
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
getch();//it will hold your output screen so you can see the output
}
In this line
printf("%30sAddition Of Numbers\n");
you did not supply a string argument for the %s format. This causes undefined behaviour.
If you want the output spaced, you could try a small modification
printf("%30s\n", "Addition Of Numbers");
in this case you are supplying a string literal to satisfy the %s format.
Additionally you must always check the return value from scanf to see that it did convert the number of arguments it was supposed to. It's a basic newbie error not to, and the root cause of hundreds of SO questions.
I am trying to figure out why I can't get this to run properly. I just want four inputs from the user, and run the calculation at the end.
#include <stdio.h>
#include <math.h>
int main(){
double amount; /* amount on deposit */
double principal; /* what's the principal */
double rate; /* annual interest rate */
int year; /* year placeholder and no. of total years */
int yearNo;
printf("What is the principal? ");
scanf("%d", &principal);
printf("What is the rate (in decimal)? ");
scanf(" .2%d", &rate);
printf("What is the principal? ");
scanf(" %d", &principal);
printf("How many years? ");
scanf(" %d\n", yearNo);
printf("%4s%21s\n", "Year", "Amount on deposit");
/* calculate the amount on deposit for each of ten years */
for (year = 1; year <= yearNo; year++){
amount = principal * pow(1.0 + rate, year);
printf("%4d%21.2f\n", year, amount);
}
return 0;
}
It properly asks for the principal and rate, but then skips over the question about Principal and asks for years. Then it just sits there waiting for a "ghost" entry?
I've been reading that the scanf() adds some whitespace when hitting enter but thought the space before the %d would fix that?
I also saw you could add do { c=getchar(); } while ( c != '\n'); after each scanf but that seems to crash the program (I added int c = 0; to the beginning too).
Thanks for any help or ideas!
EDIT:
When I change the erroneous format specifier from:
scanf(" .2%d", &rate);
to:
scanf(" %d", &rate);
I then get a crash after entering my values.
.2%d is not a valid format string.
For a start, the % has to come first. In addition, if you're after a floating point value, d is not the right character - it's for integral values.
You should be using something like %f (you don't need width or precision modifiers).
On top of that, you've made a minor mistake of not using a pointer for one of your scanf calls:
scanf(" %d\n", yearNo);
That's probably going to cause a crash, and should be changed to:
scanf(" %d\n", &yearNo);
And, as a final suggestion, it's totally unnecessary to use whitespace before (or a newline after) %d or %f family of format specifiers. The scanner automatically skips whitespace before both of those.
So, the only two scanf format strings you need in this program are "%d" and "%lf" (f is for floats, lf is for doubles).
I want to get the user input for variable L, but the scanf function is not working, and the program will jump and print the next cost statement and exit if I try to input anything.
I am new to C, and hope can get some help here. Thanks. Code below:
#include <stdio.h>
#include <conio.h>
int main()
{
float L = 0; // L is litre
float gallon;
gallon = 3.785 * L;
char x[2] = {'u', 'd'}; // u is unleaded and d is diesel
float cost;
printf("Hello, welcome to PetrolUpHere!!\n");
printf("Would u like unleaded or diesel fuel?");
scanf("%s", &x[2]);
printf("Enter the litre you want to fuel:");
scanf("%.2f", &L); //SCANF NOT WORKING
switch (x[2]) {
case 'u':
cost = 1.98 * gallon;
printf("The cost is :%.2f ", cost);
break;
case 'd':
cost = 1.29*gallon;
printf("The cost is :%.2f ",cost);
break;
}
getch();
return 0;
}
There are a number of problems here:
scanf("%s", &x[2]);
I imagine you wanted to read a string into the variable x. Instead, you're saying "read a string into memory 2 positions past where x points". In this case that memory will be out of bounds. You should do this, since you only care about one character:
char input;
scanf("%c", &input);
Your switch statement is similarly broken; x[2] is again out of bounds. Use input from the above code instead.
As others have pointed out, using %.2f is not what you want to do when reading in L. Use %f instead. Generally you should only do something like that with format specifiers when printing out variables, rather than reading them in. Eventually you won't be using scanf anyway, since it's not a particularly safe way of getting input.
Finally: it seems like your understanding of how C strings work is shaky at best. This is understandable, since this is a fairly confusing topic for anyone who hasn't worked in C before, and especially for novice programmers. Here's one explanation; I'm sure you can find many more, probably better ones if you look.
There are three problems in this much of your code (at least):
char x[2] = {'u', 'd'};//u is unleaded and d is diesel
float cost;
printf("Hello, welcome to PetrolUpHere!!\n");
printf("Would u like unleaded or diesel fuel?");
scanf("%s", &x[2]);
printf("Enter the litre you want to fuel:");
scanf("%.2f", &L); //SCANF NOT WORKING
switch (x[2]) {
x is an array of 2 char which is initialized, but is not a null terminated string.
You use scanf("%s", &x[2]), which is reading a string into data that is not part of the array x.
You then dereference x[2] in the switch statement — again accessing data that is out of bounds.
You don't check either scanf() call to ensure it was able to scan a result.
You don't print what you read immediately after you read it.
The . in the scanf() format is not valid; use "%f" (you probably do not want to use "%2f" as that would limit you to two digits maximum).
You haven't actually said what you entered in response to the 'unleaded or diesel' question.
scanf("%s", &x[2]);
Should be:
scanf("%c", &x[2]);
scanf("%.2f", &L);
Should be:
scanf("%2f", &L);
And you initialized gallon with '0.0',then your output will always be '0.0'.
Hope it works.
I just started to learn C programming.
In my book there is this piece of code:
/*Code Start*/
/*This code is use to find the simple interest*/
main ()
{
int p, n;
float r, si;
p = 1000;
n = 3;
r = 8.5;
si= p*n*r/100;
printf("%f", si);
}
/*Code end*/
The output i got was " 255.000000 "
I though i'll modify it with scanf function so i wrote this:
/*Code Start*/
main ()
{
int p, n;
float r, si;
printf("Enter value for p: \n");
scanf("%d", &p);
printf("Enter value for n: \n\n");
scanf("%d", &n);
printf("Enter valuse for r: \n\n");
scanf("%d", &r);
si= p*n*r/100;
printf("\nYour Simple Interest is %f\n\n", si);
}
/*Code End*/
No matter what values i give to p,n,r the answer i get is always 0.000000..
I also tried giving the values, p=1000, n=3, r=8.5 but still i get 0.000000..
Change the specifier in scanf. You're using %d instead of %f:
scanf("%f", &r);
^
First side note: the code looks kind of bad (no return type for main ?!). Are you sure it's a good book ?
Second side note: using floats today is kind of pointless. Maybe you
should use doubles ?
Firstly, your main problem: The %d specifier is only for integers, not floats or doubles. Use %f for floats.
In addition, the main should return an int, this will do:
int main() {
/* your code */
return 0;
}
Finally, I would recommend you make better use of white-space as it will vastly help with readability once you start making larger programs.
Use %f conversion specification to read a float:
scanf("%f", &r);
%d means it reads a decimal integer and not a float.
r is a float, but you're reading it in using %d as a scanf specifier, which expects an int.
The real culprit in your code is the line scanf("**%d**", &r).
%d is the format specifier for integer value, as you declared r as float then use %f instead of %d.
i.e. scanf("%f", &r)
Change Either
int p, n;
float r, si;
to
int p, n,r;
float si;
or change formate specifier in scanf("%d", &r); %d to %f.
when you declare r as an integer r=8 will be considered, in that case scanf("%d", &r); will be accepted. and your program get compiled and executed.
both declaration and formate specifier should be same.
my suggestion is to use %.2f when dealing with money. which will give like 10.00 which is the correct formate.