如何找到剩余部分

时间:2015-08-09 22:23:31

标签: c++

我尝试使用modulo(%)运算符。但每次我看到一条消息,表明我的应用程序已停止工作。这是我的代码:

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;
}

4 个答案:

答案 0 :(得分:2)

int A;
int B;
int C;
C=A%B;

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

答案 1 :(得分:1)

读取尚未初始化的变量(例如ABC)是未定义的行为。

答案 2 :(得分:0)

你的变量B没有用值初始化,但是编译器似乎非常友好地将它设置为0,所以A%B(内部)除以零,这是&n #39; ta有效的数学运算,因此发生严重错误。

答案 3 :(得分:0)

欢迎使用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;
}
相关问题