除法函数随机整数需要打印出商和余数
division function random integer need quotient and remainder printed out
嗨,我
写这段代码是为了有程序,同时使用小于 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);
}
- 除法函数使用变量
divident
和divisor
在 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;
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 除法函数随机整数需要打印出商和余数