简体   繁体   English

C++:编写一个程序,当输入“-6.5”时终止

[英]C++: Write a program which terminates when “-6.5” is entered

The task is to write a simple program which takes an integer and calculates its factorial if an even number is entered, or checks if the number is prime, if an odd number is entered.任务是编写一个简单的程序,该程序采用 integer 并在输入偶数时计算其阶乘,或者在输入奇数时检查数字是否为素数。 The program repeats until the value "-6.5" is entered.程序重复,直到输入值“-6.5”。 I added a condition for the loop to stop when that value is entered but instead i get an infinitely repeating loop of the input prompt when that value (or any other decimal) is entered.我添加了一个条件,让循环在输入该值时停止,但是当输入该值(或任何其他小数)时,我得到一个输入提示的无限重复循环。 Why is this happening?为什么会这样?

#include <iostream>
using namespace std;
int main ()
{
    int num;
    do
    {
    int choice;
    int factorial=1;
    int count=0;
    cout<<"Enter a number: \n";
    cin>>num;
    if (num>1)
    {
    cout<<"To calculate factorial, enter an even number\n";
    cout<<"\nTo check if a number is Prime or not, enter an odd number\n";
    cin>>choice;

    {
        if (choice%2==0)
    {
        for (int i=num; i>=1; i--)
    {
        factorial=factorial*i;
    }
        cout<<endl;
        cout<<"The factorial of "<<num <<" equals " <<factorial;
        cout<<endl;

    }
    if (choice%2==1)

    {
    for (int i=2;i<num;i++)
        {
           if (num%i==0)
           {
            ++count;
           }

        }
    if (count==0)
    {
        cout<<endl;
        cout<<num <<" is prime.\n ";
    }
    else if (!(count==0))
    {
        cout<<endl;
        cout<<num <<" is not prime.\n";
    }

    }  
    }   
    }

    }
    while (!(num==-6.5));

} 

As a quick glance all your numbers are ints, which will only hold whole numbers and no decimals.快速浏览一下,所有数字都是整数,它只包含整数,没有小数。

Start with changing any number that is required to hold a decimal with a double or a float (pick which one is best for your application).首先更改使用双精度或浮点数保存小数所需的任何数字(选择最适合您的应用程序的数字)。

See what happens once you change the numbers.看看更改数字后会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM