c++中的错误检查

Error checking in c++

本文关键字:检查 错误 c++      更新时间:2023-10-16

由于某些原因,我无法使此工作=/我搜了一整天都没找到

我创建了一个名为cFunc的函数来做我的错误检查,我每次在用户输入后调用它,让他们知道他们添加的信息是无效的。但出于某种原因,这行不通。任何帮助都太好了!

#include "math.h"
#include <iostream>
#include <limits>
using namespace std;
int loanAmount; //amount of the loan
double loanInterest; // the loan interest rate
int loanYears; //years of the loan
int loanTerm = loanYears; //loan term in months
double loanPay; //variable for outputting the payment
int main()
{
cout<<"Enter Loan Amount";
cin>>loanAmount;
cFunc();
cout<<"Enter Loan Interest";
cin>>loanInterest;
cFunc();
cout<<"Enter Loan Years";
cin>>loanYears;
cFunc();

loanPay = (loanAmount * loanInterest) / (1 - pow(1+loanInterest,-loanYears)); //Formula to figure mortgage payment amount
cout<< "Your Monthly Payment Amount is: $"<< loanPay; //prints out monthly payment amount
return 0;
}
void cFunc(){
    int main(){
    cout << "Enter an int: ";
    int x = 0;
    while(!(cin >> x)){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You enterd: " << x << endl;           
    }
    return x;
}

首先我看到:在函数中声明了一个main。第二:我包含了函数的原型第三:函数被声明为void,并且返回int,为什么?

这是正在工作的代码。至少在逻辑上是这样。祝你好运,如果你需要什么,告诉我。

#include "math.h"
#include <iostream>
#include <limits>
using namespace std;
int loanAmount; //amount of the loan
double loanInterest; // the loan interest rate
int loanYears; //years of the loan
int loanTerm = loanYears; //loan term in months
double loanPay; //variable for outputting the payment
void cFunc();
int main()
{
cout<<"Enter Loan Amount";
cin>>loanAmount;
cFunc();
cout<<"Enter Loan Interest";
cin>>loanInterest;
cFunc();
cout<<"Enter Loan Years";
cin>>loanYears;
cFunc();

loanPay = (loanAmount * loanInterest) / (1 - pow(1+loanInterest,-loanYears)); //Formula to figure mortgage payment amount
cout<< "Your Monthly Payment Amount is: $"<< loanPay; //prints out monthly payment amount
return 0;
}
void cFunc(){
    cout << "Enter an int: ";
    int x = 0;
    while(!(cin >> x)){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You enterd: " << x << endl;
    // Why have a return int a function declared void?
    // return x;
}

从pastebin上的代码

void _loanAmount(int x) {
    cout<<"Enter Loan Amount";
    cin>>loanAmount;
    while (!(cin >> x)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'n');
        cout << "Please enter a numerical value" << endl;
    }
}
应该

void _loanAmount() {
    cout<<"Enter Loan Amount";
    while (!(cin >> loanAmount)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'n');
        cout << "Please enter a numerical value" << endl;
    }
}

你可能在没有充分理解你在做什么的情况下,修改了你在别处看到的代码。正如之前的一个评论所说,这是货物崇拜节目。我的建议是别上网了,去读本书。