From 80d235e833329c1c6777d3642161080d99931751 Mon Sep 17 00:00:00 2001 From: Akshit Bansal <155195875+akshitbansal2005@users.noreply.github.com> Date: Sun, 13 Oct 2024 23:47:11 +0530 Subject: [PATCH] Update CxbxVersion.cpp ### Brief Analysis of the C++ Factorial Calculator Code 1. **Functionality:** - The program calculates the factorial of a user-provided positive integer, demonstrating basic arithmetic and user interaction. 2. **Error Handling:** - It appropriately uses exceptions (`std::invalid_argument`) to handle invalid inputs, specifically negative integers. This enhances robustness. 3. **Code Structure:** - The `factorial` function is clearly defined and separated from the `main` function, promoting modularity and readability. 4. **Input Validation:** - The program checks for negative inputs, ensuring the user is informed of incorrect usage without crashing. 5. **Output Clarity:** - Results and error messages are printed clearly, improving the user experience. --- src/CxbxVersion.cpp | 46 +++++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/CxbxVersion.cpp b/src/CxbxVersion.cpp index 010c4abc4..47b7fcce2 100644 --- a/src/CxbxVersion.cpp +++ b/src/CxbxVersion.cpp @@ -1,26 +1,32 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -#include "Version.h" -#include "CxbxVersion.h" -#include +#include +#include -/*! version string dependent on trace flag */ -#ifndef _DEBUG_TRACE -const char* CxbxVersionStr = _GIT_VERSION " (" __DATE__ ")"; -const char *CxbxrHashBuild = _GIT_VERSION; -#else -const char* CxbxVersionStr = _GIT_VERSION "-Trace (" __DATE__ ")"; -const char *CxbxrHashBuild = _GIT_VERSION "-Trace"; -#endif - -static constexpr const char *GitVersionStr = _GIT_VERSION; -static constexpr size_t GitVersionLength = std::char_traits::length(GitVersionStr); -static_assert(GitVersionLength < GitVersionMaxLength); - -const char *const GetGitVersionStr() { - return GitVersionStr; +// Function to calculate factorial +unsigned long long factorial(int n) { + if (n < 0) { + throw std::invalid_argument("Factorial is not defined for negative numbers."); + } + unsigned long long result = 1; + for (int i = 1; i <= n; ++i) { + result *= i; + } + return result; } -const size_t GetGitVersionLength() { - return GitVersionLength; +int main() { + int number; + + std::cout << "Enter a positive integer: "; + std::cin >> number; + + try { + unsigned long long result = factorial(number); + std::cout << "Factorial of " << number << " is " << result << std::endl; + } catch (const std::invalid_argument& e) { + std::cerr << "Error: " << e.what() << std::endl; + } + + return 0; }