ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

Creating a Discount Calculator in C

Автор: vlogize

Загружено: 2025-09-26

Просмотров: 1

Описание: Learn how to build a simple discount calculator in C language. Understand the logic behind user input and get correct discounted prices with this easy-to-follow guide.
---
This video is based on the question https://stackoverflow.com/q/62970976/ asked by the user 'Sowmo0509' ( https://stackoverflow.com/u/13954183/ ) and on the answer https://stackoverflow.com/a/62970997/ provided by the user 'Abhishek Bhagate' ( https://stackoverflow.com/u/13602076/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: I want to create a discount calculator in C, using a function. I want to get the values from user. But mine is not working

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Creating a Discount Calculator in C: A Step-by-Step Guide

Are you trying to develop a discount calculator in C but are running into issues? Building a program that calculates discounts can be a useful project, whether for learning or practical purposes. In this guide, we’ll guide you through creating a straightforward discount calculator and addressing common pitfalls along the way.

The Problem

You want to create a discount calculator function that can take user input for the total price and the discount percentage, then calculate the final price after the discount is applied. However, you encountered an error in your code, specifically in the way you are handling user input for float values.

What Went Wrong

In your original code, you are using the format specifier %d for reading float values from user input. This is incorrect, as %d is meant for integers. The correct format specifier to read float values in C is %f.

Step-by-Step Solution

Let’s break down the solution into clear sections and correct your code.

1. Define the Discount Function

You’ve created a function named getDiscountedPrice that calculates the discounted price. Here’s the logic:

First, calculate the amount of discount by taking the percentage of the total price.

Then, subtract that discount from the total price to get the final price.

Here is the original function you wrote:

[[See Video to Reveal this Text or Code Snippet]]

This part of the code is correct and does not require any modifications.

2. Fix the Main Program

You need to ensure that the user input is correctly handled. Instead of using %d, we'll change it to %f for float values. Here’s the corrected version of the main function:

[[See Video to Reveal this Text or Code Snippet]]

3. Full Working Code

Here’s the complete code now that incorporates the changes we discussed:

[[See Video to Reveal this Text or Code Snippet]]

Conclusion

Congratulations! You now have a functioning discount calculator written in C. By simply replacing the incorrect format specifier %d with %f, the issues in your program have been resolved.

When writing programs that involve decimal numbers, always remember to use the correct format specifiers to avoid runtime errors or incorrect calculations.

Feel free to use this template and further improve or customize the calculator to meet your needs!

With this knowledge, you can confidently develop more complex programs in C, paving the way for deeper learning in programming. Happy coding!

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
Creating a Discount Calculator in C

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

Москва согласилась на капитуляцию? / Кремль внезапно предлагает подписать договор

Москва согласилась на капитуляцию? / Кремль внезапно предлагает подписать договор

Python

Python

Удаляем свои фото, выходим из чатов, скрываем фамилию? Как избежать штрафов

Удаляем свои фото, выходим из чатов, скрываем фамилию? Как избежать штрафов

Изучение PostgreSQL с нуля / #4 – Связи между таблицами (JOIN)

Изучение PostgreSQL с нуля / #4 – Связи между таблицами (JOIN)

Как в 1С не остаться на уровне новичка в 2026 году?

Как в 1С не остаться на уровне новичка в 2026 году?

Как Cursor переворачивает разработку и может погубить Github

Как Cursor переворачивает разработку и может погубить Github

Самый короткий тест на интеллект Задача Массачусетского профессора

Самый короткий тест на интеллект Задача Массачусетского профессора

ЛУЧШАЯ БЕСПЛАТНАЯ НЕЙРОСЕТЬ Google, которой нет аналогов

ЛУЧШАЯ БЕСПЛАТНАЯ НЕЙРОСЕТЬ Google, которой нет аналогов

Компьютерные сети 2025

Компьютерные сети 2025

The Complete Mozart Amadeus Movie Soundtrack - All Mozart composed music & variations

The Complete Mozart Amadeus Movie Soundtrack - All Mozart composed music & variations

Обучение EXCEL. УРОК 2: Основы форматирования. Первая таблица. Рабочая область. Горячие клавиши.

Обучение EXCEL. УРОК 2: Основы форматирования. Первая таблица. Рабочая область. Горячие клавиши.

Behebung des numpy.int64 AttributeError in Sklearn Regressionsmodellen

Behebung des numpy.int64 AttributeError in Sklearn Regressionsmodellen

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

Что обнаружено после взлома разработчика электронных повесток?

Что обнаружено после взлома разработчика электронных повесток?

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

Vintage Floral Free Tv Art Wallpaper Screensaver Home Decor Samsung Oil Painting Digital Wildflower

Vintage Floral Free Tv Art Wallpaper Screensaver Home Decor Samsung Oil Painting Digital Wildflower

КАК УСТРОЕН TCP/IP?

КАК УСТРОЕН TCP/IP?

Deep House Mix 2024 | Deep House, Vocal House, Nu Disco, Chillout Mix by Diamond #3

Deep House Mix 2024 | Deep House, Vocal House, Nu Disco, Chillout Mix by Diamond #3

4 Hours Chopin for Studying, Concentration & Relaxation

4 Hours Chopin for Studying, Concentration & Relaxation

Настройка VS Code за 30 минут — НАСТРОЙКА которая работает!

Настройка VS Code за 30 минут — НАСТРОЙКА которая работает!

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]