c1-1 (779455), страница 3

Файл №779455 c1-1 (Numerical Recipes in C) 3 страницаc1-1 (779455) страница 32017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 3)

One of us wasonce asked, for a scavenger hunt, to find the date of a Friday the 13th on which themoon was full. This is a program which accomplishes that task, giving incidentallyall other Fridays the 13th as a by-product.#include <stdio.h>#include <math.h>#define ZON -5.0#define IYBEG 1900#define IYEND 2000Time zone −5 is Eastern Standard Time.The range of dates to be searched.int main(void) /* Program badluk */{void flmoon(int n, int nph, long *jd, float *frac);long julday(int mm, int id, int iyyy);int ic,icon,idwk,im,iyyy,n;float timzon = ZON/24.0,frac;long jd,jday;printf("\nFull moons on Friday the 13th from %5d to %5d\n",IYBEG,IYEND);for (iyyy=IYBEG;iyyy<=IYEND;iyyy++) {Loop over each year,for (im=1;im<=12;im++) {and each month.jday=julday(im,13,iyyy);Is the 13th a Friday?idwk=(int) ((jday+1) % 7);if (idwk == 5) {n=(int)(12.37*(iyyy-1900+(im-0.5)/12.0));This value n is a first approximation to how many full moons have occurredsince 1900.

We will feed it into the phase routine and adjust it up or downuntil we determine that our desired 13th was or was not a full moon. Thevariable icon signals the direction of adjustment.icon=0;for (;;) {flmoon(n,2,&jd,&frac);Get date of full moon n.frac=24.0*(frac+timzon); Convert to hours in correct time zone.if (frac < 0.0) {Convert from Julian Days beginning at--jd;noon to civil days beginning at midfrac += 24.0;night.}if (frac > 12.0) {++jd;frac -= 12.0;} elsefrac += 12.0;if (jd == jday) {Did we hit our target day?printf("\n%2d/13/%4d\n",im,iyyy);printf("%s %5.1f %s\n","Full moon",frac,Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited.

To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).than one place) becomes true. At that point you wish to exit the loop and proceedwith what comes after it.

In C the structure is implemented with the simple breakstatement, which terminates execution of the innermost for, while, do, or switchconstruction and proceeds to the next sequential instruction. (In Pascal and standardFORTRAN, this structure requires the use of statement labels, to the detriment of clearprogramming.) A typical usage of the break statement is:14Chapter 1.Preliminaries}}}}return 0;}If you are merely curious, there were (or will be) occurrences of a full moonon Friday the 13th (time zone GMT−5) on: 3/13/1903, 10/13/1905, 6/13/1919,1/13/1922, 11/13/1970, 2/13/1987, 10/13/2000, 9/13/2019, and 8/13/2049.Other “standard” structures.Our advice is to avoid them.

Everyprogramming language has some number of “goodies” that the designer just couldn’tresist throwing in. They seemed like a good idea at the time. Unfortunately theydon’t stand the test of time! Your program becomes difficult to translate into otherlanguages, and difficult to read (because rarely used structures are unfamiliar to thereader). You can almost always accomplish the supposed conveniences of thesestructures in other ways.In C, the most problematic control structure is the switch...case...defaultconstruction (see Figure 1.1.1), which has historically been burdened by uncertainty,from compiler to compiler, about what data types are allowed in its control expression.Data types char and int are universally supported.

For other data types, e.g., floator double, the structure should be replaced by a more recognizable and translatableif. . .else construction. ANSI C allows the control expression to be of type long,but many older compilers do not.The continue; construction, while benign, can generally be replaced by anif construction with no loss of clarity.About “Advanced Topics”Material set in smaller type, like this, signals an “advanced topic,” either one outside ofthe main argument of the chapter, or else one requiring of you more than the usual assumedmathematical background, or else (in a few cases) a discussion that is more speculative or analgorithm that is less well-tested. Nothing important will be lost if you skip the advancedtopics on a first reading of the book.You may have noticed that, by its looping over the months and years, the program badlukavoids using any algorithm for converting a Julian Day Number back into a calendar date.

Aroutine for doing just this is not very interesting structurally, but it is occasionally useful:#include <math.h>#define IGREG 2299161void caldat(long julian, int *mm, int *id, int *iyyy)Inverse of the function julday given above. Here julian is input as a Julian Day Number,and the routine outputs mm,id, and iyyy as the month, day, and year on which the specifiedJulian Day started at noon.{long ja,jalpha,jb,jc,jd,je;Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America)." hrs after midnight (EST)");break;Part of the break-structure, a match.} else {Didn’t hit it.ic=(jday >= jd ? 1 : -1);if (ic == (-icon)) break;Another break, case of no match.icon=ic;n += ic;}1.2 Some C Conventions for Scientific Computing15}(For additional calendrical algorithms, applicable to various historical calendars, see [8].)CITED REFERENCES AND FURTHER READING:Harbison, S.P., and Steele, G.L., Jr.

1991, C: A Reference Manual, 3rd ed. (Englewood Cliffs,NJ: Prentice-Hall).Kernighan, B.W. 1978, The Elements of Programming Style (New York: McGraw-Hill). [1]Yourdon, E. 1975, Techniques of Program Structure and Design (Englewood Cliffs, NJ: PrenticeHall). [2]Jones, R., and Stewart, I. 1987, The Art of C Programming (New York: Springer-Verlag). [3]Hoare, C.A.R.

1981, Communications of the ACM, vol. 24, pp. 75–83.Wirth, N. 1983, Programming in Modula-2, 3rd ed. (New York: Springer-Verlag). [4]Stroustrup, B. 1986, The C++ Programming Language (Reading, MA: Addison-Wesley). [5]Borland International, Inc. 1989, Turbo Pascal 5.5 Object-Oriented Programming Guide (ScottsValley, CA: Borland International). [6]Meeus, J. 1982, Astronomical Formulae for Calculators, 2nd ed., revised and enlarged (Richmond, VA: Willmann-Bell). [7]Hatcher, D.A.

1984, Quarterly Journal of the Royal Astronomical Society, vol. 25, pp. 53–55; seealso op. cit. 1985, vol. 26, pp. 151–155, and 1986, vol. 27, pp. 506–507. [8]1.2 Some C Conventions for ScientificComputingThe C language was devised originally for systems programming work, not forscientific computing. Relative to other high-level programming languages, C putsthe programmer “very close to the machine” in several respects. It is operator-rich,giving direct access to most capabilities of a machine-language instruction set. Ithas a large variety of intrinsic data types (short and long, signed and unsignedintegers; floating and double-precision reals; pointer types; etc.), and a concisesyntax for effecting conversions and indirections.

It defines an arithmetic on pointers(addresses) that relates gracefully to array addressing and is highly compatible withthe index register structure of many computers.Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited.

To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).if (julian >= IGREG) {Cross-over to Gregorian Calendar produces this correcjalpha=(long)(((float) (julian-1867216)-0.25)/36524.25);tion.ja=julian+1+jalpha-(long) (0.25*jalpha);} else if (julian < 0) {Make day number positive by adding integer number ofja=julian+36525*(1-julian/36525);Julian centuries, then subtract them off} elseat the end.ja=julian;jb=ja+1524;jc=(long)(6680.0+((float) (jb-2439870)-122.1)/365.25);jd=(long)(365*jc+(0.25*jc));je=(long)((jb-jd)/30.6001);*id=jb-jd-(long) (30.6001*je);*mm=je-1;if (*mm > 12) *mm -= 12;*iyyy=jc-4715;if (*mm > 2) --(*iyyy);if (*iyyy <= 0) --(*iyyy);if (julian < 0) iyyy -= 100*(1-julian/36525);.

Характеристики

Тип файла
PDF-файл
Размер
133,25 Kb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6310
Авторов
на СтудИзбе
312
Средний доход
с одного платного файла
Обучение Подробнее