it-place.net > Уроци > C-Cplusplus
Не сте регистриран! Регистрирайте се БЕЗПЛАТНО, за да използвате услугите на сайта!

   Рубрики
 
 
 
 

 Форуми
» SEO и оптимизация
» Всичко за PHP и Perl
» Всичко за C, C++ и .NET
» Всичко за Java и JSP
» Всичко за SQL и MySQL
» Всичко за XHTML и CSS
» Презентация на сайтове
 Променливи
  1. Променливи
     
Автор  angelspasovspasov (12.02.2005 12:25)  съобщение до автора
Погледнат  4314 пъти  добави към любими
Оценка  добави коментар
Гласове  2  изпрати на приятел
Коментари  (1)  абонирай се за C-Cplusplus
    Страница 1 / 1

 




        Представете си,  че  Ви е дадена задача да изчислите 2
    на степен 10. Нашият първи опит би могъл да изглежда така:

        #include <striam.h>

        main()
        {
         // a first solution
         cout << 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
         cout << "n";
         return 0;
        }

    Написаното работи,  въпреки че ще ни се наложи да преброим два
    или три  пъти дали  сме записали  константата 2 точно 10 пъти.
    Само  тогава ще  бъдем доволни.  Нашата програма правилно дава
    отговор 1024.
        Сега обаче,  ни се налага да изчислим 2, повдигнато на
    17  степен,  а след  това на  23.  Неприятно  е  да  променяме
    програмата  си всеки  път.  Още  по-лошо, изглежда поразително
    лесно  да  се  направи    грешка    като се  постави една двойка в
    повече     или   по-малко.  Обаче,  понеже  сме  внимателни, ние
    избягваме грешките.
        Накрая ни  се налага  да  направим  таблица,  която да
    съдържа  степените  на    двойката  от  0 до 31. Ако използуваме
    литерални  константи в директни кодови последователности ще ни
    бъдат нобходими 64 реда от следния вид:

        cout << "2 raised to the power of Xt";
        cout << 2 * ... * 2;

    където Х ще се увеличава с единица за всяка кодова двойка.
        В този момент, а може би и по-рано, ние осъзнаваме, че
    трябва да има по-добър начин.  Както и наистина има. Решението
    изисква  въвеждането  на  две  понятия,  които все  още не  са
    формално дефинирани:

        1. Променливи,    които  позволяват  да се  съхраняват и
    възстановяват стойности.

        2. Съвкупност    от   управляващи   оператори,     които
    позволяват многократното изпълнение на част от програмния код.

    Например,  ето един  втори  начин за  изчисляване  на  2 на 10
    степен:
 
                                 

        #include <stream.h>

        main()
        {
         // a second more general solution
         int value = 2;
         int pow = 10;

         cout << value
              << " raised to the power of "
              << pow << ": t";

         for ( int i = 1, res = 1; i <= pow; ++i )
             {
               res = res * value;
             }

         cout << res << "n";
         return 0;
        }

    Операторът,  започващ  с  for,    се  нарича оператор  за цикъл:
    докато i  е по-малко  или равно на pow, се изпълнява тялото на
    for,  затворено  във  фигурни  скоби.    Цикълът  for се нарича
    поточно управляващ оператор.        
value, pow, res и i
         са променливи, които позволяват да
    се съхраняват, променят и възстановяват стойности.  Те са тема
    на следващите подглави. Първо, обаче, нека приложим друго ниво
    на обобщанане на  програмата  като отделим част от програмата,
    която изчислява  степента на величината и да я дефинираме като
    отделна функция.

        unsigned int
        pow ( int val, int exp )
        {
         //compute val raised to exp power
         for ( unsigned int res = 1; exp > 0; --exp );
               res = res * val;
         return res;
        }

    Всяка задача, която изисква изчисляването на някаква степен на
    дадена стойност,  сега може просто да извика pow() с подходящо
    множество  от  аргументи.   Исканата  таблица  от  степени  на
    двойката сега може да бъде получена по следния начин:
   
   

                                 

        #include <stream.h>

        extern unsigned int pow ( int, int );
        main()
        {
         int val = 2;
         int exp = 16;

         cout << "mThe Power of 2n";
         for ( int i = 0; i <= exp; ++i )
               cout << i << ": " << pow ( val, i ) << "n";
         return 0;
        }

    Таблица  1.1  представя  резултата  от    изпълнението  на  тази
    програма.

        The Power of 2

        0: 1
        1: 2
        2: 4
        3: 8
        4: 16
        5: 32
        6: 64
        7: 128
        8: 256
        9: 512
        10: 1024
        11: 2048
        12: 4096
        13: 8192
        14: 16384
        15: 32768
        16: 65536
                 Степени на 2

        Тази  реализация  на pow()  не проверява онези особени
    случаи,  когато  имаме    повдигане  на  отрицателна  степен или
    стойността - резултат е много голяма.



   


Ключови думи: c C++ програмиране променлива


Още уроци от тази рубрика


 
  • Подобни теми от myLinks
 

 1 посетител чете този урок (0 потребители и 1 гост)  
Активни потребители: ---
   
  

Еmail  
 

за хората които не четат хелп-а защото смятат че няма нищо там , надяжам се да ви разобедя в това.

The fundamental type specifiers are built from the following keywords:

char    __int8    long
double    __int16    signed
float    __int32    short
int    __int64    unsigned

From these keywords you can build the integral and floating-point types, which are together known as the arithmetic types. The modifiers long, short, signed, and unsigned can be applied to the integral types. The header file limits.h contains definitions of the value ranges for all the fundamental types.

Integral types

char, short, int, and long, together with their unsigned variants, are all considered integral data types. Integral types shows the integral type specifiers, with synonyms listed on the same line.

Integral types

char, signed char    Synonyms if default char set to signed.
unsigned char
char, unsigned char    Synonyms if default char set to unsigned.
signed char
int, signed int
unsigned, unsigned int
short, short int, signed short int
unsigned short, unsigned short int
long, long int, signed long int
unsigned long, unsigned long int

Note:    These synonyms are not valid in C++. See The three char types.

Only signed or unsigned can be used with char, short, int, or long. The keywords signed and unsigned, when used on their own, mean signed int and unsigned int, respectively.
In the absence of unsigned, signed is usually assumed. An exception arises with char.  Borland C++ lets you set the default for char to be signed or unsigned. (The default, if you don't set it yourself, is signed.) If the default is set to unsigned, then the declaration char ch declares ch as unsigned. You would need to use signed char ch to override the default. Similarly, with a signed default for char, you would need an explicit unsigned char ch to declare an unsigned char.

Only long or short can be used with int. The keywords long and short used on their own mean long int and short int.
ANSI C does not dictate the sizes or internal representations of these types, except to indicate that short, int, and long form a nondecreasing sequence with "short <= int <= long." All three types can legally be the same. This is important if you want to write portable code aimed at other platforms.

In a Borland C++ 16-bit program, the types int and short are equivalent, both being 16 bits. In a Borland C++ 32-bit program, the types int and long are equivalent, both being 32 bits. The signed varieties are all stored in two's complement format using the most significant bit (MSB) as a sign bit: 0 for positive, 1 for negative (which explains the ranges shown in 16-bit data types, sizes, and ranges and 32-bit data types, sizes, and ranges). In the unsigned versions, all bits are used to give a range of 0 - (2n - 1), where n is 8, 16, or 32.

Floating-point types

The representations and sets of values for the floating-point types are implementation dependent; that is, each implementation of C is free to define them. Borland C++ uses the IEEE floating-point formats.See the topic on ANSI implementation-specific.
float and double are 32- and 64-bit floating-point data types, respectively. long can be used with double to declare an 80-bit precision floating-point identifier: long double test_case, for example.

16-bit data types, sizes, and ranges and 32-bit data types, sizes, and ranges indicates the storage allocations for the floating-point types

Standard arithmetic conversions

When you use an arithmetic expression, such as a + b, where a and b are different arithmetic types, Borland C++ performs certain internal conversions before the expression is evaluated. These standard conversions include promotions of "lower" types to "higher" types in the interests of accuracy and consistency.
Here are the steps Borland C++ uses to convert the operands in an arithmetic expression:

1.Any small integral types are converted as shown in Methods used in standard arithmetic conversions. After this, any two values associated with an operator are either int (including the long and unsigned modifiers), or they are of type double, float, or long double.
2.    If either operand is of type long double, the other operand is converted to long double.
3.    Otherwise, if either operand is of type double, the other operand is converted to double.

4.    Otherwise, if either operand is of type float, the other operand is converted to float.
5.    Otherwise, if either operand is of type unsigned long, the other operand is converted to unsigned long.
6.    Otherwise, if either operand is of type long, then the other operand is converted to long.
7.    Otherwise, if either operand is of type unsigned, then the other operand is converted to unsigned.
8.    Otherwise, both operands are of type int.

The result of the expression is the same type as that of the two operands.

Methods used in standard arithmetic conversions

Type    Converts to    Method

char    int    Zero or sign-extended (depends on default char type)
unsigned char    int    Zero-filled high byte (always)
signed char    int    Sign-extended (always)
short    int    Same value; sign extended
unsigned short    unsigned int    Same value; zero filled
enum    int    Same value

Special char, int, and enum conversions

Note:    The conversions discussed in this section are specific to Borland C++.

Assigning a signed character object (such as a variable) to an integral object results in automatic sign extension. Objects of type signed char always use sign extension; objects of type unsigned char always set the high byte to zero when converted to int.
Converting a longer integral type to a shorter type truncates the higher order bits and leaves low-order bits unchanged. Converting a shorter integral type to a longer type either sign-extends or zero-fills the extra bits of the new value, depending on whether the shorter type is signed or unsigned, respectively.

  irrefutable на 09.03.2005 18:54

 

 
  • Интересно от Софтуер
 



IT-PLACE.NET © 2004 - 2008