• Log in or sign up for an account here: https://www.sythe.org/login

Help with variable? ;[

Joined
Mar 23, 2007
Sythe Gold
5
Messages
1,020
Age
32
Location
Funny story actually....
Okay, so I'm attempting to learn C, but I can't get my head past something..

printf ("Astronomy is %dderful \n",1);

Okay, %d is the variable, and it says what the variable is, \n",1); The variable = 1.

but why wouldn't you just say ("Astronomy is 1derful") Or whatever, instead of typing %d AND typing what %d is after the string.
 
It's useful for times when you will have data that is not static (changing). Here's an example that should help you understand. It prompts you to enter two numbers and then proceeds to display the sum of the two numbers you entered and as it is impossible to determine what the final output will be beforehand, the computer must perform a calculation based on the given input before displaying the the output which includes the result of that computation.

Code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int number_one, number_two;
  printf("Enter two numbers to be added together:\n");  
  
  scanf("%d", &number_one);
  scanf("%d", &number_two);  
  
  printf("\nThe total of your two numbers is: %d", number_one + number_two);
  
  getchar();
  getchar();
  return 0;
}
 
scanf("number_one");
scanf("number_two");
This doesn't work because the scanf() function requires two arguments to be passed.

Code:
scanf( [placeholder identifying the variable type], &Variable_to_save_to )
The first argument is a placeholder prefixed by "%" and surrounded by quotation marks. This indicates the type of variable we will be saving the input into. Some examples are %d (integer), %c (character), %s (string of characters), %f (floating point), %x (hexadecimal), etc.

The second argument is the variable you want to save the input into which in this case is "Variable_to_save_to". You prefix the second argument (the variable name) with "&" to indicate that you are referencing to its place in memory and not its value because you are looking to modify it, not just read it.

So a valid use of scanf() would essentially be:
Code:
scanf( "%c", &my_character );

Hope this clears things up somewhat, but feel free to add me on MSN anyway if you like.
 
Runescape Gamblingrunescape gambling
Back
Top