如何求余数

How to find a remainder

本文关键字:何求余      更新时间:2023-10-16

我通过使用模(%)运算符进行了尝试。但是每次我看到我的应用程序停止工作的消息。下面是我的代码:

using namespace std;
int main ()
{
    int A;
    int B;
    int C;
    C = A % B;
    cout << "What is A";
    cin >> A;
    cout << "What is B";
    cin >> B;
    cout << A % B;
    return 0;
}
int A;
int B;
int C;
C=A%B;

因此,您根据尚未设置的值AB计算C。它们可以是任何东西,因此,它们实际上是什么是未定义的,当你计算A%B时也是如此。可能B恰好为0,这会在CPU中产生算术错误。

读取未初始化的变量是未定义的行为,例如您的A, BC

您的变量B没有初始化值,但编译器似乎很友好地将其设置为0,因此A%B(内部)除零,这不是一个有效的数学操作,因此发生严重错误

欢迎来到c++ !:)

使用C,因为你正在计算它:

cout << C << endl; //outputs the computation of A % B

总之,这是一个编辑版本的代码片段。

#include <iostream> //used for cout and cin
using namespace std;
int main ()
{
   int A; //A,B,C are initialized with no values
   int B;
   int C;
   cout << "What is A";
   cin >> A; //A is given a value
   cout << "What is B";
   cin >> B; //B is given a value
   C = A % B; //previous place in the code is computing empty values. but placing this line of code AFTER values have been set, allows the program to compute.
   cout << C;
   return 0;
}