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.
This commit is contained in:
Akshit Bansal 2024-10-13 23:47:11 +05:30 committed by GitHub
parent 204dcf8801
commit 80d235e833
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 26 additions and 20 deletions

View File

@ -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 <string>
#include <iostream>
#include <stdexcept>
/*! 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<char>::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;
}