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;
Related
Code:
#include <stdio.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float per;
printf("Enter subject 1 marks out of 100 \n");
scanf("%d",s1);
printf("Enter subject 2 marks out of 100\n");
scanf("%d",s2);
printf("Enter subject 3 marks out of 100 \n");
scanf("%d",s3);
printf("Enter subject 4 marks out of 100\n");
scanf("%d",s4);
printf("Enter subject 5 marks out of 100\n");
scanf("%d",s5);
sum=s1+s2+s3+s4+s5;
per=sum/100;
if (per>60 && per<70){
printf("your percentage is %d and you get 10% schoolarship",per)
;}
else if (per>70.1 && per<90){
printf("your percentage is %d and you get 20% schoolarship",per)
;}
else {
printf("your percentage is %d and you get 30% schoolarship",per)
;}
}
Output:
I am trying to make a percentage calculator and it shows a weird output.
What am I doing wrong?
When you call scanf, it is important to pass in the address of the variable you want to store. Otherwise, scanf will not behave as you expect.
Right now, you are not passing in the address to scanf; but rather the variable itself.
So you should do something like:
scanf("%d",&s1);
instead.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I recommend reading a little bit about how scanf works at the following link.
"Following is the declaration for scanf() function.
int scanf(const char *format, ...)"
Additionally, check out this link for a few examples of scanf:
https://www.programiz.com/c-programming/c-input-output
scanf("%d", &testInteger);
The syntax is format first, then pass in the address of where you want to store the data.
scanf() requires a pointer to the value, it should be scanf("%d",&s1);
This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
Closed 7 years ago.
I managed to make this simple two part program which consists of simple print and scan functions. The first part is an addition operation and the second part asks the user for a letter and then it repeats it to the user. The first part goes well but when it finishes and is supposed to start the second part it shows the whole thing before I can input a letter.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int num1, num2 = 522;/*input a number*/ /*add 522*/
int sum; /*sum of num1 and num2*/
char let; /*Letter to put in*/
printf("Hello, my name is John Doe.\n"); /*Print "Hello my name is*/
printf("Please type a number= "); /*Ask user for num1*/
scanf("%d", &num1); /*Scan for num1*/
sum = num1 + 522; /*Add 522 to num1*/
printf("The sum of %d and %d is %d\n", num1, num2, sum);/*print num1 and sum*/
printf("Please type a letter= \n"); /*Ask user for letter*/
scanf("%c", &let); /*Scan for letter*/
printf("You typed %c\n", let); /*Show the letter input*/
return 0;
}
Change
scanf("%c", &let);
to
scanf(" %c", &let);
There is a newline character after a number is entered so that is picked by %c you need to ignore it. Note the space before %c
A better approach is flushing the input buffer after every scanf()/getchar() call.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input.
As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.
you can use getchar() function as well to clean the new line character but first method is recommended.
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.
I am trying to figure out how I can make my program read what the user is typing in, such as a numeric value in this case but I'm having trouble. Here is what I put so far. The first part of the code is just a fake name and email address that just outputs my credentials (so that shouldn't matter).
#include <stdio.h>
int main(void)
{
printf("John Smith\n");
printf("abc#abc.com\n");
/* User must enter values in feet */
int d;
printf("Enter length for side a: \n");
scanf(" %d");
return 0;
}
You forgot to put your variable into the scanf:
scanf(" %d", &d);
printf("You entered %d\n", d);
To read a value from scanf you must give it the address of the variable using (&)
Like so:
scanf(" %d",&d);
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.