提问者:小点点

如何做才能使它不在我的最后一个数字(,)之后打印?


得到两个数字,输出它们之间的素数并用逗号分隔这个数字,不要在代码末尾输出逗号。

我该怎么做才能使它不在我的最后一个数字后面打印逗号? 我不想对此代码进行太多更改

#include<iostream>
using namespace std;
int main(){
    int a,b,sum=0,x,aaa=0,primeman; 
    cin>>a;
    cin>>b;
    for (int i=a+1; i <b ;i++){
        sum+=1;
        x=0;
        for(int j=1;j<i/2;j++){
            if (i%j==0){
                x++;
            }
        }   
        if (x==1){
            cout<<i<<",";
        }
    }
}

共2个答案

匿名用户

您可以使用以下方法:

std::string delimiter("");
if (x==1) {
    std::cout << delimiter << i;
    delimiter = ",";
}

匿名用户

为了避免逗号打印在最后一个数字之后,我们可以在除第一个数字之外的每个数字之前打印逗号。 为此,我们引入了一个新的布尔变量firstElement,它将确保在输出的第一个元素之前不打印逗号。

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int a,b,x; 
    cin >> a;
    cin >> b;
    bool firstElement= true; // marker for the first element
    for (int i=a+1; i<b; i++){
        x=0;
        for(int j=2;j<=sqrt(i);j++){ // replaced "division by 2" by square root 
            if (i%j==0){
                x++;
                break; // once a number is found to be divisible by other, it is 
                       // not a prime, hence no need to check further
            }
        }   
        if(x==0){
            if(firstElement){ // if 'i' is the first element(prime number)
                cout << i;
                firstElement = false;

            }
            else{
                cout << ", " << i ;
            }
            
        }
    }
    return 0;
}

注意:我已经删除了一些未使用的变量,如sum,aaa,primeman,请看看它是否仍然需要用于其他目的。