为什么我要尝试在一个if语句中调用两个fucntions,但是在第一个完成后它忽略了另一个功能?(C )

Why do I try to call two fucntions in one if statement, but it ignores the other function after the first is completed? (C++)

本文关键字:第一个 功能 另一个 两个 一个 我要 if 语句 为什么 fucntions 调用      更新时间:2023-10-16

我已经将头撞在墙上了几个小时,浏览了线程和视频,试图弄清楚有关此代码的一些内容。除非我在调用我的加密并解密我的if语句中调用" int"并解密功能之前,它不会编译。但是,如果我这样做,则该程序将在该程序到达加密/解密部分之前终止,并好像不存在。否则,它会给我诸如"未定义的eNCRPYT(("之类的错误。我已经阅读了有关调用函数的指南,但是看来我无法正常工作。我想念什么?

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int readNumber();
int encrypt();
int decrypt();
char choice;

int main()
{
cout << endl; 
cout << "Please select one of the following: " << endl;
cout << "1. Encrypt a number " << endl;
cout << "2. Decrypt a number " << endl; 
cout << endl;
cout << "Enter choice: ";
cin >> choice; 
cout << endl;

if (choice == '1')
{
    readNumber();
    encrypt();
}

else if (choice == '2')
{
    readNumber();
    decrypt();
}

else 
{
    cout << "Invalid choice. Try again. " << endl;
    cout << endl;
}
}
int readNumber()
{
int number;
cout << "Enter the four digit number: ";
cin >> number;

if (number > 9999)
{
    cout << endl;
    cout << "Please input a four digit, non-negative number. " << endl;
    cout << endl;
    return readNumber();
} 

cout << endl;
return 0;

}
int encrypt(int number)
{
    int Num1,Num2,Num3,Num4;
Num1 = number / 1000;
Num2 = number / 100 - 10*Num1;
Num4 = number%10;
Num3 = (number%100 - Num4) / 10;

cout << "The encrypted number is: "
     << (Num4 + 7)%10
     << (Num3 + 7)%10
     << (Num2 + 7)%10
     << (Num1 + 7)%10
     << endl; 
        return 0;
 }
int decrypt(int number)
{
int Num1,Num2,Num3,Num4;
Num1 = number / 1000;
Num2 = number / 100 - 10*Num1;
Num4 = number%10;
Num3 = (number%100 - Num4) / 10;

cout << "The decrypted number is: "
     << (Num1 + 3)%10
     << (Num2 + 3)%10
     << (Num3 + 3)%10
     << (Num4 + 3)%10
     << endl; 
        return 0;
 }

您的声明函数 encryptdecrypt 没有参数,请使用/调用无参数参数。因此,您会获得带有未定义功能的链接器错误。

当您在if语句中函数调用之前添加int时,您可以用与main之前的相同函数声明替换函数调用。

可能您想要

// before main
int encrypt(int number);
int decrypt (int number);
...
// in if statements
int number = readNumber();
encrypt(number);
...
int number = readNumber();
decrypt(number);

代码不会完全产生程序,因为远期声明

using namespace std;
int readNumber();
int encrypt();
int decrypt();
...

不匹配下面实现的函数,以便编译器可以找到远期指定

int encrypt();
int decrypt();

但是链接器只能找到

int encrypt(int number)

int decrypt(int number) 

在下面实现。

但是

if (choice == '1')
{
    int readNumber();
    int encrypt();
}

会编译,因为它无能为力。它声明功能而不是调用它们。它有效地重复了您在文件顶部所做的工作

您想声明

using namespace std;
int readNumber();
int encrypt(int number);
int decrypt(int number);
...

匹配下面实现的功能,然后

int toBeEncrypted = readNumber();
int encryptedNumber = encrypt(toBeEncrypted);

调用函数并使用它们返回的值。

附录:检查所有功能中的返回值。您似乎总是返回零。

相关文章: