калькулятор c консольное приложение
Консольный калькулятор на C++
В этой статье мы рассмотрим как создать калькулятор на C++ для консоли или терминала, думаю будет очень интересно.
Также посмотрите статью «Как установить Qt 5 на Linux Ubuntu», если вы интересуетесь программированием на C++, то вам стоит установить эту IDE.
Калькулятор на C++ в консоли:
Как вы уже поняли, мы будем делать очень простой калькулятор, для консоли или терминале, зависимо на какой OS вы работаете.
В начале объявим все нужные для нас переменные:
Давайте разберём какая переменная, для чего нужна, a и b нужны для записывания чисел над которыми будем проводить действия, а в c записываем результат.
Переменная d хранит в себе знак действия, p будет использоваться для выбора действия счёта или выхода из калькулятора.
Теперь перейдём к основной программе, она не сильно большая, поэтому у вас не займёт много времени прочитать код:
Как видите, в начале мы даём выбор, начать проводить математические действия, или выйти из программы, и всё это происходит в цикле.
Если выбираем произвести действие, то в начале выбираем первое число, потом действие которое хотим совершить, зависимо от этого вводим нужный нам знак.
Всего доступно четыре, это сложение, вычитание, умножение и деление, чтобы применить, нужно ввести определённые знаки на этом этапе, это «+», «-», «*» и «/» соответственно.
Потом вводим второе число, и выводим результат, примерно так всё и работает, как видите всё очень просто.
Вывод:
В этой статье вы увидели как создать калькулятор на C++, и как видите тут всё очень просто, конечно на этом языке можно придумать что то покруче, но если вы новичок, то этого думаю вам пока хватит.
Подписываетесь на все соц-сети ещё много разных подобных статей будет.
Делаем консольный калькулятор.
На этом уроке мы напишем простенький консольный калькулятор на языке С#. Программа будет работать так: пользователь вводит операнды и оператор, а программа сообщает результат.
Double – это тип переменной с плавающей запятой, иными словами, тип, в который можно записать десятичные числа. В него поместится как значение 5, так и значение 5,45, и даже значение 5,4571601695, также в нём можно использовать и отрицательные числа.
В переменную a мы внесём первое число, которое запишет пользователь. В переменную b – второе число. А переменная res будет выводить результат математических операций с переменными а и b.
Char – это тип переменной в виде какого-либо символа, будь то буква, цифра или какой-нибудь знак. В переменную oper мы будем заносить знак математической операции над числами.
Итак, переменные объявлены, теперь нам надо узнать, что конкретно нужно посчитать пользователю, а для этого придётся считывать данные, которые он будет вводить:
Сначала мы выводим на консоль надпись о том, чтобы пользователь ввёл первое число.
В следующей строке мы присваиваем переменной a введенное пользователем число, но при этом не забываем, что введенные пользователем данные всегда имеют строковой формат string, а так как у нашей переменной тип double, то надо отконвертировать string в double соответствующим методом Convert.
То же самое проделываем с переменной oper, но конвертируем string уже не в double, а в char, потому что переменная oper имеет такой тип данных. Точно то же самое, что было с переменной a проделываем и с переменной b, так как они одинакового типа.
Числа получены. Но пока неизвестно, как ими оперировать, так как главное для нас – узнать что за знак скрывается в переменной oper, и уже исходя из этого, производить операции над числами:
Для этого мы используем оператор условия if (если). Первая строка звучит примерно так: если в переменной oper записан знак “+”, то.. мы присваиваем переменной res сумму переменных a и b и выводим ответ на экран. Рассмотрим код программы полностью:
После написания кода откомпилируем ее и получим результат:
Для закрепления материала рекомендую самостоятельно записать каждую строчку кода в свой созданный проект и изучить ход выполнения программы.
Create a console calculator in C++
The usual starting point for a C++ programmer is a «Hello, world!» application that runs on the command line. That’s what you’ll create first in Visual Studio in this article, and then we’ll move on to something more challenging: a calculator app.
Prerequisites
Create your app project
Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. A project contains all the options, configurations, and rules used to build your apps. It also manages the relationship between all the project’s files and any external files. To create your app, first, you’ll create a new project and solution.
If you’ve just started Visual Studio, you’ll see the Visual Studio Start dialog box. Choose Create a new project to get started.
Otherwise, on the menubar in Visual Studio, choose File > New > Project. The Create a new project window opens.
In the list of project templates, choose Console App, then choose Next.
Make sure you choose the C++ version of the Console App template. It has the C++, Windows, and Console tags, and the icon has «++» in the corner.
In the Configure your new project dialog box, select the Project name edit box, name your new project CalculatorTutorial, then choose Create.
An empty C++ Windows console application gets created. Console applications use a Windows console window to display output and accept user input. In Visual Studio, an editor window opens and shows the generated code:
Verify that your new app builds and runs
The template for a new Windows console application creates a simple C++ «Hello World» app. At this point, you can see how Visual Studio builds and runs the apps you create right from the IDE.
To build your project, choose Build Solution from the Build menu. The Output window shows the results of the build process.
To run the code, on the menu bar, choose Debug, Start without debugging.
Press a key to dismiss the console window and return to Visual Studio.
You now have the tools to build and run your app after every change, to verify that the code still works as you expect. Later, we’ll show you how to debug it if it doesn’t.
Edit the code
Now let’s turn the code in this template into a calculator app.
In the CalculatorTutorial.cpp file, edit the code to match this example:
To save the file, enter Ctrl+S, or choose the Save icon near the top of the IDE, the floppy disk icon in the toolbar under the menu bar.
To run the application, press Ctrl+F5 or go to the Debug menu and choose Start Without Debugging. You should see a console window appear that displays the text specified in the code.
Close the console window when you’re done.
Add code to do some math
It’s time to add some math logic.
To add a Calculator class
Go to the Project menu and choose Add Class. In the Class Name edit box, enter Calculator. Choose OK. Two new files get added to your project. To save all your changed files at once, press Ctrl+Shift+S. It’s a keyboard shortcut for File > Save All. There’s also a toolbar button for Save All, an icon of two floppy disks, found beside the Save button. In general, it’s good practice to do Save All frequently, so you don’t miss any files when you save.
You should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. If you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer window.
In Calculator.h, remove the Calculator(); and
Calculator(); lines that were generated, since you won’t need them here. Next, add the following line of code so the file now looks like this:
A pop-up appears that gives you a peek of the code change that was made in the other file. The code was added to Calculator.cpp.
Currently, it just returns 0.0. Let’s change that. Press Esc to close the pop-up.
Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and
If you build and run the code again at this point, it will still exit after asking which operation to perform. Next, you’ll modify the main function to do some calculations.
To call the Calculator class member functions
Now let’s update the main function in CalculatorTutorial.cpp:
Build and test the code again
Now it’s time to test the program again to make sure everything works properly.
Press Ctrl+F5 to rebuild and start the app.
Debug the app
Since the user is free to type anything into the console window, let’s make sure the calculator handles some input as expected. Instead of running the program, let’s debug it instead, so we can inspect what it’s doing in detail, step-by-step.
To run the app in the debugger
Set a breakpoint on the result = c.Calculate(x, oper, y); line, just after the user was asked for input. To set the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. A red dot appears.
Now when we debug the program, it always pauses execution at that line. We already have a rough idea that the program works for simple cases. Since we don’t want to pause execution every time, let’s make the breakpoint conditional.
Now we pause execution at the breakpoint specifically if a division by 0 is attempted.
Useful windows in the debugger
Whenever you debug your code, you may notice that some new windows appear. These windows can assist your debugging experience. Take a look at the Autos window. The Autos window shows you the current values of variables used at least three lines before and up to the current line. To see all of the variables from that function, switch to the Locals window. You can actually modify the values of these variables while debugging, to see what effect they would have on the program. In this case, we’ll leave them alone.
You can also just hover over variables in the code itself to see their current values where the execution is currently paused. Make sure the editor window is in focus by clicking on it first.
To continue debugging
Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line in the program’s execution. F10 is also known as Step Over. You can use Step Over to move from line to line, without delving into the details of what is occurring in each part of the line. In general you should use Step Over instead of Step Into, unless you want to dive more deeply into code that is being called from elsewhere (as you did to reach the body of Calculate ).
Continue using F10 to Step Over each line until you get back to the main() function in the other file, and stop on the cout line.
This result happens because division by zero is undefined, so the program doesn’t have a numerical answer to the requested operation.
To fix the «divide by zero» error
Let’s handle division by zero more gracefully, so a user can understand the problem.
Make the following changes in CalculatorTutorial.cpp. (You can leave the program running as you edit, thanks to a debugger feature called Edit and Continue):
Now press F5 once. Program execution continues all the way until it has to pause to ask for user input. Enter 10 / 0 again. Now, a more helpful message is printed. The user is asked for more input, and the program continues executing normally.
When you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the debugger is still running your old code, and has not yet updated it with your changes. The debugger pops up a dialog to inform you when this happens. Sometimes, you may need to press F5 to refresh the code being executed. In particular, if you make a change inside a function while the point of execution is inside that function, you’ll need to step out of the function, then back into it again to get the updated code. If that doesn’t work for some reason and you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at the top of the IDE, then start debugging again by entering F5 or by choosing the green «play» arrow beside the stop button on the toolbar.
Understanding the Run and Debug shortcuts
Close the app
Add Git source control
Now that you’ve created an app, you might want to add it to a Git repository. We’ve got you covered. Visual Studio makes that process easy with Git tools you can use directly from the IDE.
Git is the most widely used modern version control system, so whether you’re a professional developer or you’re learning how to code, Git can be very useful. If you’re new to Git, the https://git-scm.com/ website is a good place to start. There, you can find cheat sheets, a popular online book, and Git Basics videos.
To associate your code with Git, you start by creating a new Git repository where your code is located. Here’s how:
In the status bar at the bottom-right corner of Visual Studio, select Add to Source Control, and then select Git.
In the Create a Git repository dialog box, sign in to GitHub.
The repository name auto-populates based on your folder location. By default, your new repository is private, which means you’re the only one who can access it.
Whether your repository is public or private, it’s best to have a remote backup of your code stored securely on GitHub. Even if you aren’t working with a team, a remote repository makes your code available to you from any computer.
Select Create and Push.
After you create your repository, you see status details in the status bar.
The first icon with the arrows shows how many outgoing/incoming commits are in your current branch. You can use this icon to pull any incoming commits or push any outgoing commits. You can also choose to view these commits first. To do so, select the icon, and then select View Outgoing/Incoming.
The second icon with the pencil shows the number of uncommitted changes to your code. You can select this icon to view those changes in the Git Changes window.
To learn more about how to use Git with your app, see the Visual Studio version control documentation.
The finished app
Congratulations! You’ve completed the code for the calculator app, built and debugged it, and added it to a repo, all in Visual Studio.
Next steps
The usual starting point for a C++ programmer is a «Hello, world!» application that runs on the command line. That’s what you’ll create in Visual Studio in this article, and then we’ll move on to something more challenging: a calculator app.
Prerequisites
Create your app project
Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. A project contains all the options, configurations, and rules used to build your apps. It also manages the relationship between all the project’s files and any external files. To create your app, first, you’ll create a new project and solution.
On the menubar in Visual Studio, choose File > New > Project. The New Project window opens.
On the left sidebar, make sure Visual C++ is selected. In the center, choose Windows Console Application.
In the Name edit box at the bottom, name the new project CalculatorTutorial, then choose OK.
An empty C++ Windows console application gets created. Console applications use a Windows console window to display output and accept user input. In Visual Studio, an editor window opens and shows the generated code:
Verify that your new app builds and runs
The template for a new windows console application creates a simple C++ «Hello World» app. At this point, you can see how Visual Studio builds and runs the apps you create right from the IDE.
To build your project, choose Build Solution from the Build menu. The Output window shows the results of the build process.
To run the code, on the menu bar, choose Debug, Start without debugging.
Press a key to dismiss the console window and return to Visual Studio.
You now have the tools to build and run your app after every change, to verify that the code still works as you expect. Later, we’ll show you how to debug it if it doesn’t.
Edit the code
Now let’s turn the code in this template into a calculator app.
In the CalculatorTutorial.cpp file, edit the code to match this example:
To save the file, enter Ctrl+S, or choose the Save icon near the top of the IDE, the floppy disk icon in the toolbar under the menu bar.
To run the application, press Ctrl+F5 or go to the Debug menu and choose Start Without Debugging. If you get a pop-up that says This project is out of date, you may select Do not show this dialog again, and then choose Yes to build your application. You should see a console window appear that displays the text specified in the code.
Close the console window when you’re done.
Add code to do some math
It’s time to add some math logic.
To add a Calculator class
Go to the Project menu and choose Add Class. In the Class Name edit box, enter Calculator. Choose OK. Two new files get added to your project. To save all your changed files at once, press Ctrl+Shift+S. It’s a keyboard shortcut for File > Save All. There’s also a toolbar button for Save All, an icon of two floppy disks, found beside the Save button. In general, it’s good practice to do Save All frequently, so you don’t miss any files when you save.
You should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. If you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer window.
In Calculator.h, remove the Calculator(); and
Calculator(); lines that were generated, since you won’t need them here. Next, add the following line of code so the file now looks like this:
Currently, it just returns 0.0. Let’s change that. Press Esc to close the pop-up.
Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and
If you build and run the code again at this point, it will still exit after asking which operation to perform. Next, you’ll modify the main function to do some calculations.
To call the Calculator class member functions
Now let’s update the main function in CalculatorTutorial.cpp:
Build and test the code again
Now it’s time to test the program again to make sure everything works properly.
Press Ctrl+F5 to rebuild and start the app.
Debug the app
Since the user is free to type anything into the console window, let’s make sure the calculator handles some input as expected. Instead of running the program, let’s debug it instead, so we can inspect what it’s doing in detail, step-by-step.
To run the app in the debugger
Set a breakpoint on the result = c.Calculate(x, oper, y); line, just after the user was asked for input. To set the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. A red dot appears.
Now when we debug the program, it always pauses execution at that line. We already have a rough idea that the program works for simple cases. Since we don’t want to pause execution every time, let’s make the breakpoint conditional.
Now we pause execution at the breakpoint specifically if a division by 0 is attempted.
Useful windows in the debugger
Whenever you debug your code, you may notice that some new windows appear. These windows can assist your debugging experience. Take a look at the Autos window. The Autos window shows you the current values of variables used at least three lines before and up to the current line.
To see all of the variables from that function, switch to the Locals window. You can actually modify the values of these variables while debugging, to see what effect they would have on the program. In this case, we’ll leave them alone.
You can also just hover over variables in the code itself to see their current values where the execution is currently paused. Make sure the editor window is in focus by clicking on it first.
To continue debugging
Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line in the program’s execution. F10 is also known as Step Over. You can use Step Over to move from line to line, without delving into the details of what is occurring in each part of the line. In general you should use Step Over instead of Step Into, unless you want to dive more deeply into code that is being called from elsewhere (as you did to reach the body of Calculate ).
Continue using F10 to Step Over each line until you get back to the main() function in the other file, and stop on the cout line.
This result happens because division by zero is undefined, so the program doesn’t have a numerical answer to the requested operation.
To fix the «divide by zero» error
Let’s handle division by zero more gracefully, so a user can understand the problem.
Make the following changes in CalculatorTutorial.cpp. (You can leave the program running as you edit, thanks to a debugger feature called Edit and Continue):
Now press F5 once. Program execution continues all the way until it has to pause to ask for user input. Enter 10 / 0 again. Now, a more helpful message is printed. The user is asked for more input, and the program continues executing normally.
When you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the debugger is still running your old code, and has not yet updated it with your changes. The debugger pops up a dialog to inform you when this happens. Sometimes, you may need to press F5 to refresh the code being executed. In particular, if you make a change inside a function while the point of execution is inside that function, you’ll need to step out of the function, then back into it again to get the updated code. If that doesn’t work for some reason and you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at the top of the IDE, then start debugging again by entering F5 or by choosing the green «play» arrow beside the stop button on the toolbar.
Understanding the Run and Debug shortcuts
Close the app
Congratulations! You’ve completed the code for the calculator app, and built and debugged it in Visual Studio.