除法函数随机整数需要打印出商和余数

division function random integer need quotient and remainder printed out

本文关键字:余数 打印 函数 随机 整数 除法      更新时间:2023-10-16
嗨,我

写这段代码是为了有程序,同时使用小于 100 => 的随机整数除法函数,返回 qoutient 和余数并将它们打印在输出中,但似乎我不起作用,你能帮忙哪一部分是错误的。

    #include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
using namespace std;
 int division(int& remainder,int qoutient)
{ 
int dividant;
int divisor;
    int quotient=dividant/divisor;      
   int remainder=dividant%divisor;
}
int main()
{
    int dividant =(rand()%99);
    int divisor =(rand()%99);
    int qoutient;
    int remainder_result;
    srand(time(NULL));
    do{qoutient=division(dividant,divisor);
    cout<<"this is q:"<<qoutient<<endl;
    cout<<"remainder"<<remainder_result<<endl;}
    while(dividant>divisor);

    }
  • 除法函数使用变量 dividentdivisor 在 Main 中声明,这超出了函数的界限,会导致错误。 为了使用这些变量,您需要使用参数将这些变量传递到函数中。
  • 你还将除法函数声明为 void,不返回任何内容,但在 do while 循环中将其用作语句。为了让函数返回一个值,你需要用你想要返回的类型替换 void,在这个可以 int ,并在函数末尾返回一个值。
  • srand(time(NULL)) 放在初始 rand 函数之后,这意味着 rand 函数将返回与 rand 尚未播种相同的值,然后是种子 rand。您需要在rand()呼叫之前发出srand(time(NULL))

我建议你阅读更多关于c ++概念的信息,你在这个程序中没有太多权利以及一些非常混乱的编码技术。

您有编译错误。 除法函数引用未声明的变量。 您需要参数化这些变量,或更改除法函数;无论如何,该函数都无法访问在 Main 的作用域中声明的变量。

下面是来自 IDEOne 的编译错误/警告列表:

prog.cpp: In function ‘void division(int&, int)’:
prog.cpp:11: error: ‘dividant’ was not declared in this scope
prog.cpp:11: error: ‘divisor’ was not declared in this scope
prog.cpp:11: warning: unused variable ‘quotient’
prog.cpp: In function ‘int main()’:
prog.cpp:23: error: void value not ignored as it ought to be
prog.cpp:25: error: ‘remainder’ was not declared in this scope
prog.cpp:28: error: expected `;' before ‘}’ token
prog.cpp:20: warning: unused variable ‘remainder_result’

修复这些错误后,请告诉我们情况。 我还建议您注意警告,因为它们可能指示代码中的其他问题。

代码有很多问题,所以我可能误解了你想做什么。 这是基于我的理解的固定代码。 我冒昧地更改了您的输出,以便它显示完整操作的数据,以便您可以检查结果:

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
void division(int dividend, int divisor, int& quotient, int& remainder)
{ 
    quotient = dividend / divisor;      
    remainder = dividend % divisor;
}
int main()
{
    srand(time(NULL));    
    int dividend = rand() % 99;
    int divisor = rand() % 99;
    int quotient, remainder;
    division(dividend, divisor, quotient, remainder);
    cout << dividend << "/" << divisor << " = " << quotient << " remainder: " << remainder << endl;
    return 0;
}