如果语句,我需要帮助。TT在第一次有一个完美的正方形或两位数的数字时首次工作,但是在第一次为其他数字做之后,是否有一种方法可以使此操作不实现?
谢谢
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
int dice()
{
return rand()%6+1;
}
string check(int tempspot, string &message)
{
if(tempspot == 11 || tempspot == 22 || tempspot == 33 || tempspot == 44 || tempspot == 55 || tempspot == 66 || tempspot == 77 || tempspot == 88 || tempspot == 99) {
message = "go to jail";
return message;
}
if(sqrt(tempspot) * sqrt(tempspot) == tempspot) {
message = "perfect square";
return message;
}
else
return "";
}
int main()
{
int sum=0;
string message;
srand(time(NULL));
cout.precision(ios::right);
cout<<"Rolls ";
cout.precision(ios::left);
cout.width(10);
cout<<"Temp-Spot";
cout.precision(ios::right);
cout.width(10);
cout<<"Prize";
cout.width(10);
cout<<"Message";
do {
cout<<"n"<<dice();
cout.precision(ios::left);
sum +=dice();
cout.width(10);
cout<<sum<<"n";
cout.width(25);
check(sum, message);
if(message == "perfect square") {
cout<<"+10";
sum += 10;
}
else if(message == "go to jail") {
cout<<"10";
sum = 10;
}
cout.width(20);
cout<<message;
}while(sum<=100);
return 0;
}
问题在您的检查功能中。
if(sqrt(tempspot( * sqrt(tempspot(== tempspot(始终为true
因此,当不满足11,22的条件等于11,22时,程序将始终返回完美的正方形。
您的问题是将"消息"传递到该函数中作为参考。只有在其中一个条件为真时,该参考才发生更改,如果它们都是错误的,则没有设置为"。如果这两个检查都是错误的,那么您正在返回";但是返回值被丢弃了,因此与此无关。
一个快速修复是确保在默认情况下存储空白消息。在这种情况下,您可以选择摆脱返回值,因为您只需要通过参考或获得返回值,而不需要两者。
void check(int tempspot, string &message)
{
if(tempspot == 11 || tempspot == 22 || tempspot == 33 || tempspot == 44 || tempspot == 55 || tempspot == 66 || tempspot == 77 || tempspot == 88 || tempspot == 99) {
message = "go to jail";
}
else if(sqrt(tempspot) * sqrt(tempspot) == tempspot) {
message = "perfect square";
}
else
{
message = ""; // this line was missing
}
}
另一个更好的想法可能是通过完全参考并使用返回值删除通行证。您只需要一个或另一个,并且在函数的客户端使用返回值更清晰:
string check(int tempspot)
{
string message; // string for message is now local to function
if(tempspot == 11 || tempspot == 22 || tempspot == 33 || tempspot == 44 || tempspot == 55 || tempspot == 66 || tempspot == 77 || tempspot == 88 || tempspot == 99) {
message = "go to jail";
}
else if(sqrt(tempspot) * sqrt(tempspot) == tempspot) {
message = "perfect square";
}
else
{
message = "";
}
return message; // only return once in this spot, cleaner
}
用法更改为:
message = check(num);
,由于声誉较低,我无法对现有帖子发表评论,所以我在这里发布以解决Tiago指出的问题。
完美的正方形是一个整数,可以表示为两个相等整数的乘积。例如, 100 是一个完美的正方形,因为它等于 10x10 。如果 n 是一个整数,则 nxn 是一个完美的正方形。
因此,要检查完美的正方形,请检查sqrt(tempspot)
调用的结果是否足够。尝试将sqrt()
调用打入Integer(检查
(int)sqrt(tempspot) == sqrt(tempspot)
应该足够并给出预期的结果(