Hello, I'm new to C, can you explain a couple of things ...

#include <stdio.h> #define N 1000 // Что означает эта строка, Что такое #define и "c чем его едят" main() { int i,q; q = 0; srand(time(NULL)); for (i=0; i<N; i++) if (rand()%100 % 2 == 0) q += 1; printf("%.2f%%\n", (float)q/N * 100); // Зачем нужен такой вывод "%.2f%%"? } 

What is #define and “what do you eat it with?” (This is the second line of code)

What does printf print at the "% .2f %%" format string? (last line)

  • int main() . Using rand() requires #include <stdlib.h> . Using time() requires #include <time.h> . And where did the question about "Why such a conclusion" come from? So what about no output in the program? - AnT
  • I was interested in why there are two percent worth, these: 2f %% - Elvin
  • Well, maybe this is how it was necessary to formulate a question? - AnT
  • @Elvin knowing the answer, reformulate the question so that others who encounter a similar question can find the answer here. - Lex Hobbit
  • 3
    It seems that all this is told in any textbook on C? - andreymal

2 answers 2

#define is a preprocessor directive, a program that prepares a C / C ++ program for compilation.

The #define directive is used to replace frequently used constants, keywords, operators, or expressions with some identifiers.

In your case, the code you write will be replaced by:

 main() { int i,q; q = 0; srand(time(NULL)); for (i=0; i<1000; i++) if (rand()%100 % 2 == 0) q += 1; printf("%.2f%%\n", (float)q/1000 * 100); } 

More difficult example for understanding:

 #define MAX(x,y) ((x)>(y))?(x):(y) Эта директива заменит фрагмент t=MAX(i,s[i]); на фрагмент t=((i)>(s[i])?(i):(s[i]); 

As for printf , the first argument is the output format string.

%.2f%% broken into 2 parts:

  • % .2f is a two-point decimal floating point decimal
  • %% - it's a sign %

    define is a preprocessor directive. Literally can be translated as "replace". It is in this example that it is used to declare a constant N. ps: this is, so to speak, an old school way of declaring constants. In the process of compiling the program, the first link is the preprocessor. It will replace all N by 1000 in this file. In general, for these purposes, it is better to use the const operator.

    "% .2f %%" is special. characters to form the output string. For more information http://www.c-cpp.ru/content/printf

    • one
      The language in this case is C. In the C language, it is precisely #define that is used, not const , and absolutely nothing “old school” in this. In C, const does not work as a substitute for #define . Here, const would work, but in general - no. - AnT