Итак, функция. Что это такое? Функция выполняет служебное действие, например вычисление, и возвращает значение. Вызвать функцию можно, написав её имя и передав ей аргументы, в нужном месте вашей программы. Чем же полезна функция? Сейчас объясню на очень простом примере! Например, Вы пишите простенькую программу, которая вычисляет среднее арифметическое трёх чисел, потом умножает полученный результат на каждое число и отнимает их сумму. Неважно зачем вам такая программа, это ведь пример ;-). Вот она (пишем в модуле):
Sub Main()
Dim a As Integer объявляем переменную для первого числа
Dim b As Integer объявляем переменную для второго числа
Dim c As Integer объявляем переменную для третьего числа
a = InputBox("Введите первое число") получаем первое число
b = InputBox("Введите второе число") получаем второе число
c = InputBox("Введите третье число") получаем третье число
проделываем нужную операцию над числами
выводим результат на экран
MsgBox (((((a + b + c) / 3) * a) * b) * c) - (a + b +c)
End Sub
Вроде бы всё нормально. А теперь представте себе, что программа начала ширится и формулой приходится пользоваться из разных мест программы и Вы должны поэтому её кругом писать 8:-O !!!
Да, некрасиво получается... Для этого можно воспользоваться функцией, которая будет иметь эту формулу и только ждать своего вызова и ваших чисел ;-)! Напишем такую функцию и назовём её, например FuncX (вне пределов подпрограммы Sub): объявляем функцию и задаём передаваемые аргументы
Public Function FuncX(a, b, c) As Integer присваевает себе значение формулы
FuncX = (((((a + b + c) / 3) * a) * b) * c) - (a + b + c)
End Function
Есть! А теперь Вы можете вызывать функцию из любого места вашей программы, написав её имя и передав три числа a, b и с:
FuncX (a, b, c) или FuncX(4, 5, 6)
и не надо больше этой длинной формулы! Вместо
(((((a + b + c) / 3) * a) * b) * c) - (a + b +c)
Теперь можно писать
FuncX(a, b, c)
Неправда это удобней? Надеюсь я обьяснил понятно ;)?
Примечание: передаваемые значения функции изменяются! Напрмер:
Function ABC (X,Y)
ABC = (2 * X) + (2 * Y)
End Function
Теперь X равно 2 * Х, а Y равно 2 * Y, т.е. их значения удвоились. Для того чтобы переданные значения не изменялись то в скобках нужно писать перед аргументом ByVal. Например:
Function ABC ( ByVal X, ByVal Y)
Сами того не подозревая, мы очень часто используем функции. Например InputBox. Смотрите:
A = InputBox (Prompt, Title)
А - это результат, возвращаемый функцией. InputBox - это имя функции. Prompt и Title - передаваемые значения. Но функция это стандартна.
Другие работы по теме:
Шпаргалка по численным методам
{кофф линейноного уавнения} a:=y2-y1 b:=x1-x2 c:=-x1*(y2-y1)+y1*(x2-x1) {лежит ли точка на прямой} p:=false; if (x3-x1)*(y2-y1)-(y3-y1)*(x2-x1)=0 then p:=true;
Шпаргалка по численным методам
Определение точки пересечения отрезков, расстояния между точками, сортировка выбором, сортировка обменом, двоичный поиск, сортировка бинарными вставками.
Консольное приложение на Дельфи
Хоть и консольные приложения уже давно вышли из моды, с помощью них можно легко делать рутинные операции. Они занимают не так много места, не требовательны к ресурсам и быстро выполняются.
Basic
МИНИСТЕРСТВО ОБЩЕГО И ПРОФЕССИОНАЛЬНОГО ЮБРАЗОВАНИЯ РФ ТАМБОВСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ КАФЕДРА ГАПС Курсовая работа по информатике
Для чего нужна процедура Sub?
Sub это то же самое, что и Function, только она не возвращает значение, а производит какое-нибудь действие. Например вывод на экран сообщения или манипулирование несколькими свойствами.
Jefferson Essay Research Paper I feel that
Jefferson Essay, Research Paper I feel that I would be considered a Jeffertonian because I think the common man should run the federal government, like Jefferson thought. I think the federal government
Archaeologists Essay Research Paper Archaeologists must question
Archaeologists Essay, Research Paper Archaeologists must question their sources in order to gain appropriate knowledge from them. Some questions archaeologist may ask include; What is it? What is it made from? What size is it? Where did it come from? When was it made and by whom? What was its function? Does this source contain evidence about the topic? What is its significance? How has this source been interpreted by others? What else was found with it? What does this source tell us about its society? Once these questions have been answered, and all data collected an archaeologist can begin to formulate a conclusion about his or her find.
Feminization Essay Research Paper Although anabolic
Feminization Essay, Research Paper . Although anabolic steroids are derived from a male sex hormone, men who take them may actually experience a ?feminization? effect along with a decrease in normal male sexual function.. Although anabolic steroids are derived from a male sex hormone, men who take them may actually experience a ?feminization? effect along with a decrease in normal male sexual function..
To Use Calculus Or Not To Use
Calculus? Essay, Research Paper Jamie Burton Period 1 Calculus To Use Calculus, or Not to Use Calculus? That is the Question In the past, if you have studied Algebra and Trigonometry, then your knowledge has prepared you to master the next step: calculus. Calculus is complicated, but not quite as bad as everyone thinks.
Gods Gift To Calculators The Taylor Series
Essay, Research Paper Gods Gift to Calculators: The Taylor Series It is incredible how far calculators have come since my parents were in college, which was when the square root key came out. Calculators since then
Ts Eliot
’s View On Poe Essay, Research Paper Cats Meets The Raven What is an author? What does it matter who is speaking? These questions posed by Michel Foucault lead the reader of his essay in many directions and to multitudes of questions. The ideas presented in T.S. Eliot s essay From Poe to Valery illustrate three different ways of examining Poe, his work, and also the influence of his work.
Information About Transgenic Organisms Essay Research Paper
Transgenic Organism, plant, animal, or bacteria that has been genetically modified to contain a gene from a different species. The new gene is inherited by offspring in the same way as the organism’s own genes. The transgenic condition is achieved by injecting the foreign gene into the fertilized egg or into embryonic cells.
Philosophy That People And Animals Are Persons
But Not Machines Essay, Research Paper What Constitutes Being a Person? What constitutes being a ?person?? The question of the week. No clear cut conclusions have been reached. No argument has been presented without significant loop holes. So, what to think? Well, within this chaos we all seem to have an opinion.
Object Oriented Programming Essay Research Paper THE
Object Oriented Programming Essay, Research Paper THE ADVANTAGES OF OBJECT-ORIENTED PROGRAMMING USING C++ Object-oriented programming is a new way of approaching the job of programming. Programming over the years has evolved to accommodate the increased complexity of programs. (1) Structured, easy to understand programming has been around since the late 60’s.
Assembly Language Essay Research Paper When programming
Assembly Language Essay, Research Paper When programming in assembly language, we have to specify operations in a much greater level of detail than we would have to do in a high level language. Furthermore, we get relatively little help from the assembler in finding errors. Assemblers can only check the syntax of each line, and check that every symbol or label used is defined somewhere.
Absolute Value Functions Essay Research Paper Absolute
Absolute Value Functions Essay, Research Paper Absolute Value Functions (y=a|x-b|+c) In an absolute value function “a” represents the slope of the equation. The slope is counted up or down, then both left and right thus producing the function’s “V” shape and its symmetry. If a*0 in the equation, then the “V” has and upward direction, but if a*0 then the “V” has a downward direction.
Calculus Essay Research Paper Calculus
Calculus Essay, Research Paper Calculus “One of the greatest contributions to modern mathematics, science, and engineering was the invention of calculus near the end of the 17th century,”
Fuctions And Roles Of Protiens Carbohydr Essay
, Research Paper In this assesment the student will identify the chareracteristics and roles of carbohydrates, proteins, lipids, and nucleic acids in a living system. Write a 4 paragraph report describing the atoms in the compound building blocks, types, structure, and function of each. The student must also describe what they would do if they were given a jar with an unknown substance to find out wether or not it contained any of the substances listed above.
Positive Functions Of Poverty Essay Research Paper
?Positive Functions of Poverty? Poverty and the poor satisfy American because it is useful to their society. Without the poor who would do all the ?dirty work?? The first, second, and third functions that Herbert J. Hans mention deals with the economy. Every society has jobs that the poor would work for. Some of the dirty work can be dangerous, temporary, and underpaid.
Pleasantville Essay Research Paper The other day
Pleasantville Essay, Research Paper The other day while over a friend s house we started watching the movie Pleasantville. At first I thought it looked terrible and was actually about to leave when I realized that the whole movie was based on the functionalist perspective of sociology.
Opinion II Essay Research Paper Choose one
Opinion II Essay, Research Paper Choose one of these that you believe to be the most important function of art criticism. Using the function as your guide, write a short critical essay of the work titled Global Groove by Nam June Paik.?Offer insight into the relationships between art and life, and science, economics, politics, religion, ethic, etc? is believed to be the most important function of art criticism.
Water Retention Essay Research Paper Water retention
Water Retention Essay, Research Paper Water retention is the most simplest way to avoid too much fat, disgestive programs, toxins, and muscle sorenesses. Water is found all over the earth and also about 60 to 70
How The Functions Of The Settl Essay
, Research Paper How the functions of the settlement many have influenced its business structure. All settlements are services centres just like Ilkley is a service centre for the people of that area. It needs to provide banks, hospitals, schools, dentist and doctors for inhabitants.
Cell Structure And Function Essay Research Paper
CELL STRUCTURE AND FUNCTION All living things are made of the same basic building blocks, cells. A human is made of 65 trillion cells. Cells are everywhere, on you skin, in your blood, and even on your tongue. In fact, your blood is clear but red blood cells are what make your blood red. Most living things are made up of many cells but some are made of only one cell, like amebas, paramecium, fungi, protists, monerans, and bacteria.
Dreams Essay Research Paper DREAMSDreams are an
Dreams Essay, Research Paper DREAMS Dreams are an essential part of our lives. It is the most important part of the sleep that people need in order to function. In order to understand dreams, one must understand the importance and function of dreams and the different theories surrounding dreams. I have several thoughts and opinions on the widely popularized theories, as well as well as ideas of my own.
Experimental Ablation Essay Research Paper Experimental ablation
Experimental Ablation Essay, Research Paper Experimental ablation is one of the most common research methods. It consists of removal or destruction of part of the brain of an experimental animal for the purpose of studying the functions of that region of the brain. Most often tissue is destroyed rather than removed.
Mind And The Brain Essay Research Paper
To ask the question ?Is the mind a function of the brain?, you first have to understand that the mind and the brain are two separate entities. The brain is the most important organ of the human body. It controls everything from waking up in the morning to walking to class. The brain is the message center of the body, it tells the heart to expand and contract in order to circulate blood; and the diaphragm to move up and down so that you are able to breathe.
Principles Of Management Essay Research Paper Management
Principles Of Management Essay, Research Paper Management is a set of activities directed at an organization’s resources with the aim of achieving organizational goals in an efficient and effective manner. The first function of management is planning and decision making. Planning is setting and organization’s goals and deciding how best to achieve them.
Аналіз та обчислення дужкових виразів
Реферат на тему: Аналіз та обчислення дужкових виразів У розділі 9 розглядалися дужкові арифметичні вирази, мова яких породжується розширеною LA(1)-граматикою G2: