ГОУВПО
Уфимский государственный авиационный технический университет
Кафедра Информатики
ПОЯСНИТЕЛЬНАЯ ЗАПИСКА
к контрольной работе по информатике
Программирование на Visual Basic
Уфа 2009 г.
Задание № 1. Сумма ряда
Условие задачи:
Для числового ряда найти
а) сумму членов числового ряда при М=10;
б) точное значение суммы членов числового ряда, вычисленное по формуле Sum2=15е;
в) погрешности вычисления суммы членов числового ряда (абсолютную и относительную) по отношению к точному значению суммы членов числового ряда.
Решение:
Составим блок-схему алгоритма решения задачи (представлена на рисунке слева).
Итак, для решения задачи используем переменные:
М (количество членов вычисляемого числового ряда);
f (вспомогательная переменная, вычисляющая для цикла факториал);
Sum1 (сумма членов числового ряда);
Sum2 (точное значение суммы);
Err1 (абсолютная погрешность);
Err2 (относительная погрешность);
и определимся с типом данных, который они могут содержать. Значения переменных M и k будут короткими целыми (Integer), значение f – длинным целым (Long), а значения переменных Sum1, Sum2, Err1,Err2 – вещественные удвоенной точности [].
Для ввода значений переменной M, а также вывода результатов используются текстовые поля (объект TextBox). Чтобы сделать поля для вывода неизменяемыми, при определении характеристик поля в строке Enable укажем False [].
Составим текст программы (приведен с комментариями).
Public Class Form1
Private Sub ButtonOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOK.Click
' описание переменных:
Dim M As Integer ' количество членов числового ряда
Dim Sum1 As Double, Sum2 As Double ' сумма и точная сумма ряда
Dim Err1 As Double, Err2 As Double ' абсолютная и относительная погрешности
Dim k As Integer, f As Long ' вспомогат.переменные
' для организации цикла и подсчета факториала
' количество членов числового ряда вводятся в форме
M = Val(TextM.Text)
' вычисления
f = 1
Sum1 = 0
For k = 1 To M
f = f * k
Sum1 = Sum1 + (k + 1) ^ 3 / f
Next k
Sum2 = 15 * 2.718281828495
Err1 = Sum2 - Sum1
Err2 = Err1 / Sum2 * 100
' вывод результатов вычислений в поля формы
TextSum1.Text = Format(Sum1, "0.00000")
TextSum2.Text = Format(Sum2, "0.00000")
TextErr1.Text = Format(Err1, "0.00000000")
TextErr2.Text = Format(Err2, "0.00000000")
End Sub
Private Sub ButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCancel.Click
End
End Sub
End Class
На рис.1 представлен вариант реализации формы приложения:
Рисунок 1 – Вычисление суммы ряда
Задание № 2. Работа с массивами
Условие задачи:
Дан двумерный массив (матрица) размером NxN.
1. Определить сумму элементов, значения которых кратны заданному числу F.
2. Найти местоположения (номера индексов) минимальных элементов массива.
Решение:
Составим блок-схему алгоритма решения задачи
Программа будет содержать несколько «циклов в цикле» в виду того, что организует работы с массивами.
Текст программы
Public Class Form1
описание переменных уровня модуля: массив
Dim Arr(100, 100) As Integer
Dim N As Integer ' количество элементов массива
Private Sub ButtonGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGenerate.Click
описание переменных:
Dim Amin As Integer, Amax As Integer ' границы значений элементов массива
Dim i As Integer, j As Integer ' вспомогат.переменные
для организации цикла
' количество элементов массива и границы значений вводятся в форме
N = Val(TextN.Text)
Amin = Val(TextMin.Text)
Amax = Val(TextMax.Text)
' создание массива с помощью генератора случайных чисел
Dim Str1 As String
ListArray.Items.Clear() ' количество столбцов в поле вывода массива
For i = 0 To N - 1
Str1 = ""
For j = 0 To N - 1
Arr(i, j) = Amin + Int(Rnd() * (Amax - Amin))
Str1 = Str1 + Space(3) + Str(Arr(i, j))
Next j
ListArray.Items.Add(Str1)
Next i
End Sub
Private Sub ButtonOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOK.Click
' описание переменных:
Dim F As Integer ' число (вводимое) для поиска кратных элементов массива
Dim Fsum As Long ' сумма (искомая) кратных элементов массива
Dim Amin As Integer ' значение минимального элемента
Dim i As Integer, j As Integer ' вспомогат.переменные
' для организации цикла
' число для поиска кратных элементов вводится в форме
F = Val(TextF.Text)
If F = 0 Then Exit Sub
' вычисления
Fsum = 0
If N > 0 Then Amin = Arr(0, 0)
For i = 0 To N - 1
For j = 0 To N - 1
If Arr(i, j) / F = Int(Arr(i, j) / F) Then Fsum = Fsum + Arr(i, j)
If Amin > Arr(i, j) Then Amin = Arr(i, j)
Next j
Next i
' вывод результатов вычислений в поля формы
LabelSum.Text = Fsum
LabelMin.Text = Amin
' очистка полей для повторных нажатий кнопки "Вычислить"
ListMin.Items.Clear()
For i = 0 To N - 1
For j = 0 To N - 1
If Arr(i, j) = Amin Then
ListMin.Items.Add("элемент (" + Str(i + 1) + ";" + Str(j + 1) + ")")
End If
Next j
Next i
End Sub
Private Sub ButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCancel.Click
End
End Sub
End Class
На рис.2 представлен вариант реализации формы приложения.
Для вывода суммы элементов, кратных заданному числу и минимальных элементов используются поля Label [].
Рисунок 2 – Работа с массивами
Задание № 3. Работа со строковыми данными
Условие задачи:
Дана строка, заканчивающаяся точкой. Подсчитать, сколько в ней слов.
Решение:
Чтобы определить количество слов в строке, составим цикл, который будет проверять каждый символ в строке, начиная со второго, на совпадение с пробелом. Чтобы исключить возможность ошибки (на случай, если в одном интервале между словами окажется больше одного пробела), поставим дополнительное условие: символ, следующий до проверяемого, не должен являться пробелом. Т.е, программа будет считать пробелы, которые следуют за каким-либо другим символом. А так как интервалов между словами на 1 меньше, чем самих слов, добавим к полученной сумме пробелов единицу (но только при условии, что длина строки не равна нулю, т.е. ни одного слова не введено).
Текст программы
Public Class Form1
Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
' описание переменных:
Dim Str1 As String ' вводимая строка
Dim S As Integer ' количество слов в строке
Dim i As Integer ' вспомогат.переменные для организации цикла
Str1 = TextStr1.Text
S = 0
' поиск пробелов в строке:
' каждый пробел после некоторого символа добавляет слово
' (начальные пробелы и несколько пробелов подряд игнорируются)
For i = 2 To Len(Str1)
If Mid(Str1, i, 1) = " " And Mid(Str1, i - 1, 1) <> " " Then
S = S + 1
End If
Next i
If Len(Trim(Str1)) > 0 Then S = S + 1
' вывод результатов
TextS.Text = S
End Sub
Private Sub ButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCancel.Click
End
End Sub
End Class
На рис.2 представлен вариант реализации формы приложения
Рисунок 3 – Работа со строковыми данными
Список использованной литературы
VisualBasic-Крепкий орешек!: Вводный курс в VisualBasic. – Режим доступа: vb.hut
Иванюк, А. VisualBasic: Магия простоты
Культин, Н.Б VisualBasic. Освой на примерах/Н.Б. Культин. – СПб, 2004. -288с., ил
Другие работы по теме:
на тему
Объектно-ориентированное программирование (ооп) представляет собой новую стадию эволюционного развития технологии программирования
Визуальное программирование
Визуализация - это процесс графического отображения сложных процессов (в данном случае построения) на экране компьютера в виде графических примитивов (графических фигур).
Что такое DirectX?
DirectX представляет собой набор технологий и инструментов, которые позволяют создавать разработчику игры и мультимедиа приложения с неслыханным во времена MS-DOS качеством графики и звука.
Программирование и основы алгоритмизации 3
МИНИСТЕРСТВО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ ГОСУДАРСТВЕННОЕ ОБЩЕОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ПРОФЕССИОНАЛЬНОГО ОБРАЗОВАНИЯ КАМСКАЯ ГОСУДАРСТВЕННАЯ ИНЖЕНЕРНО - ЭКОНОМИЧЕСКАЯ
Модульное программирование 5
МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ Лабораторная работа №3 по дисциплине «Информатика и программирование» Москва, 2010 « Модульное программирование».
Мови та системи програмування
ІНФОРМАТИКА Тема: Мови та системи програмування Однією з найпоширеніших мов з програмування серед сучасних мов високого рівня, що використовуються в ПК, є мова Visual BASIC.
Информационная поисковая система
Автономно некоммерческая организация Гуманитарно-инженерный колледж Курсовая работа по дисциплине: «Технологии разработки программных продуктов»
Color Theory Essay Research Paper Color TheoryColor
Color Theory Essay, Research Paper Color Theory Color theory encompasses a multitude of definitions, concepts and design applications. All the information would fill several encyclopedias. As an introduction, here are a few basic concepts.
Light Matter Essay Research Paper Inner LightIn
Light Matter Essay, Research Paper Inner Light In order to understand what light is one has to understand how vision works. The process of visual perception is incredibly complex, involving many functions of the brain. In Arthur Zajonc’s book “Catching the Light,” he writes, “?vision requires far more than a functioning physical organ.
Baby Eye Testing Essay Research Paper U
Baby Eye Testing Essay, Research Paper U OF T PROFESSORS DEVISE BETTER WAY TO TEST SIGHT IN BABIES In a darkened room at Toronto’s Hospital for Sick Children, a baby, its head dotted with electrodes, sits in its mother’s lap and watches flashing black and white checkerboards and stripes on a television screen.
Senseless A False Sense Of Perception Essay
, Research Paper Senseless: A False Sense of Perception I feel as though I have no choice but to be a skeptic about our ability to know the world on the sense experience given the information that is being
Convergence Of The Twain Essay Research Paper
“The Convergence of the Twain” Personification is “endowing inanimate objects or abstract ideas with life or human characteristics” (Kirszner 2058). In the poem “The Convergence of the Twain” the author?s use of personification allows the reader to make a more fluid transition from the past to the present.
The NonDesigner
’s Design Book Essay, Research Paper The Non-Designer s Design Book By Robin Williams I chose this book because I am very interested in the design of a page, whether it be an advertisement, invitation, or feature story. I learned some important principles to follow. This book was easy to read and understand.
Programming Languaguages Essay Research Paper Programming LanguagesA
Programming Languaguages Essay, Research Paper Programming Languages A programming language is a set of English-like instructions that includes a set of rules for putting the instructions together to create commands. A translator changes the English-like commands into numeric code that the computer can understand.
Costa Sakellariou Essay Research Paper Costa Sakellariou
Costa Sakellariou Essay, Research Paper Costa Sakellariou Visual art can definitely be seen as a language. With every artist there is always some sort of meaning that they are trying to convey to the viewers of their work. The means of how they deliver that message is the language in which their work uses. In Costa Sakellariou?s work I especially felt there was some sort of language being spoken.
Learning Styles Essay Research Paper Every person
Learning Styles Essay, Research Paper Every person learns differently. From kindergartner to postgraduate levels, only students can do the earning, and they do it in their own particular, individual learning styles. Some children pick something up the first time they hear it. Others may not grasp a concept until they?ve had the chance to see it in print, or to write it themselves.
Learning Styles Essay Research Paper LEARNING STYLESPeople
Learning Styles Essay, Research Paper LEARNING STYLES People not only learn at different rates, but also in different ways. Some people want everything written down, others prefer to listen. Some prefer small group settings rather than large group discussions; others like to listen to a lecture and translate it into pictorial doodles in a notebook.
Learning Styles Compare
& Contrast Essay, Research Paper Learning Styles The purpose of this paper is to identify and compare the meaning as well as the differences of two learning styles as they relate to both the academic and professional realm. I have chosen these two styles because I believe the majority of people are either visual or auditory learners.
The Brain
’s Cerebral Cortex Essay, Research Paper The brain is three pounds of tissue that are part of the nervous system. It is one of the two basic parts and contains a bout 100 billion nerve cells.
Visual Art Essay Research Paper VISUAL ARTS
Visual Art Essay, Research Paper VISUAL ARTS “The physical impossibility of death in the mind of someone living” By Damien Hirst (photo courtesy of the saatchi collection)
Dragon Ball Z Web Pages Essay Research
Paper When I think of cartoons, I think of Dragon Ball Z. dragon Ball Z is an Anime series from Japan, currently airing on cartoon Network. When I received this assignment I
Memory Essay Research Paper Memory is the
Memory Essay, Research Paper Memory is the process of storing and retrieving information in the brain. Memory is viewed as a three-step process, which include sensory memory, short-term memory, and long-term memory. Along with memory there is also forgetting. There are two types of forgetting, availability and accessibility.
Dover Beach Essay Research Paper Dover Beachby
Dover Beach Essay, Research Paper ?Dover Beach? by: Matthew Arnold In the poem ?Dover Beach? by: Matthew Arnold there is a lot of irony, appeal to the auditory and visual sense, and illusions. The tone in this poem is very sad and dismal, but he shows us how to keep faith and hope in spite of that and how important being honest, true, and faithful to one another, really is.
Design Structure Essay Research Paper Basic ideas
Design Structure Essay, Research Paper Basic ideas and Concepts of Software DesignAn Interface to the End-UserThe Project Management System was designed with the goal that the end-user can handle the system on his own.The interactive user interface is based on the Windows interface.The interface programs use standard software of the market like Visual Basic, Microsoft Access and Crystal Reports.DocumentationThe software should be documented.
What Are Visual Defects And How Common
Are They ? Essay, Research Paper What Are Visual Defects and How Common Are They ? Nate Schackow 2nd Period December 17, 1996 The human eye does alot more than allowing you to see. It is very
Basic TrainingMen And Women Together Essay Research
Paper Should Men and Women Take Basic Training Together The Untied States Armed Forces consist of the Army, Navy, Air Force, and Marines; it has been in existence for many years. The first step of military life once someone joins is basic training. Just as the name implies, it is here where a recruit learns the first skills of being a warrior and how to fight battles.