Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我正在尝试在两个给定数字之间添加数字。例如,如果给定的数字是2和5,则2 + 3 + 4 + 5 = 14。我的代码的问题在于,我没有设置a,b和总和,但是我没有设置它们的值。

#include <stdio.h>

int main() {
    int a, b, sum;
    printf("%d\n", a);
    printf("%d\n", b);
    scanf_s("%d", a);
    scanf_s("%d", b);
    for (int x = a; x <= b; x++) {
        sum += x;

    }
    printf("%d\n", sum);
    return sum;

}

最佳答案

如果您要按照示例将2到5相加,

int a = 2;
int b = 5;

// Or for input from the user
scanf("%d",&a); // Note, for real you need to validate and do error handling
scanf("%d",&b); // Note, for real you need to validate and do error handling

int sum = 0;


sum始终从0开始。

a是循环的开始,因此将其设置为较低的数字。

b是循环的结尾,因此将其设置为较高的数字。

关于c - 在两个给定数字之间加数字? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42769010/

10-11 22:47
查看更多