鱼C论坛

 找回密码
 立即注册
查看: 3852|回复: 3

小甲鱼哥sqrt_02这个程序你弄错了没讲明白!

[复制链接]
发表于 2011-12-1 01:02:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>

int sqrt_02(int question);
void main( void )
{
int question = 49, answer;
       
        answer = sqrt_02( question );
        if(question < 0 )
                printf( "Error: sqrt returns %d\n, answer" );
        else
                printf( "The square root of %d is %d\n", question, answer );
}
int sqrt_02(int question)
{
        int temp=question/2;
        while(1)
        {
       
                if( temp*temp==question)
                        return temp;
                else
                temp-=1;
        }
}这个题是为了开平方, 上面此程序输入50进入死循环 因为while(1)的存在 小甲鱼哥你把程序改为
#include <stdio.h>

int sqrt_02(int question);
void main( void )
{
int question = 49, answer;
       
        answer = sqrt_02( question );
        if(answer < 0 )
                printf( "Error: sqrt returns %d\n, answer" );
        else
                printf( "The square root of %d is %d\n", question, answer );
}
int sqrt_02(int question)
{
        int temp=question/2;
        while(temp--)
        {
       
                if( temp*temp==question)
                        return temp;
                else
        return -1;
        }
}
可是这个程序错误,能纠正一下么!此时也是死循环!求大神指点下! 怎么让此程序更加接近人性化!使得程序更加有抵抗力!比如输入错误 能偶提示从新输入!

               


                               
登录/注册后可看大图
该贴已经同步到 空手套小白狼的微博
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-12-1 15:22:24 | 显示全部楼层
#include <iostream>
#define eps 1e-5;
using namespace std;
double sqrt_1(double);
int main()
{unsigned int num;
cout<<"Enter:"
while(!(cin>>num))
{cin.clear();
while(cin.get()!='\n')
continue;
cout<<"Please enter a number:";
cin>>num;
cout<<"Answer:"<<sqrt_1(num);}
return 0;
}
double sqrt_1(double n)
{
        if(n<0)
                cout<<"Error!"<<endl;
                return n;
                double ans;
                double low,up;
                low=0,up=n;
                ans=(low+up)/2;
                while(ans*ans-n>eps||ans*ans-n<-eps)
                {
                        if(ans*ans>n)
                                up=ans;
                        else
                                low=ans;
                        ans=(up+low)/2;
                }
                return ans;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-12-3 22:49:16 | 显示全部楼层
return -1在while括号外,没有else;或者在括号里写成else if(temp==0) return -1;
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-12-3 22:53:28 | 显示全部楼层
if( temp*temp==question)
改为:
if( temp*temp<=question && (temp+1)*(temp+1)>question)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-24 05:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表